0

If I have within my scope something a variable like so:

$scope.myListOLD = 
 [ 
 { title: "First title", content: "First content" }, 
 { title: "Second title", content: "" },
 { title: "Third title", content: "" }, 
 { title: "Fourth title", content: "Fourth content" } 
 ];

How could I create a new scope variable that removed any empty values on a specific field? (In this case content).

$scope.myListNEW = 
 [ 
 { title: "First title", content: "First content" }, 
 { title: "Fourth title", content: "Fourth content" } 
 ];
Phil
166k25 gold badges265 silver badges269 bronze badges
asked Sep 13, 2016 at 4:42

2 Answers 2

3

Use Array.prototype.filter

function removeIfStringPropertyEmpty(arr, field) {
 return arr.filter(function(item) {
 return typeof item[field] === 'string' && item[field].length > 0;
 });
}
var $scope = {"myListOLD":[{"title":"First title","content":"First content"},{"title":"Second title","content":""},{"title":"Third title","content":""},{"title":"Fourth title","content":"Fourth content"}]};
$scope.myListNEW = removeIfStringPropertyEmpty($scope.myListOLD, 'content');
console.log($scope.myListNEW);

answered Sep 13, 2016 at 4:46
Sign up to request clarification or add additional context in comments.

1 Comment

Works beautifully! Thanks!
0

var app = angular.module('app', []);
app.controller('homeCtrl', function ($scope) {
 $scope.myListOLD = 
 [ 
 { title: "First title", content: "First content" }, 
 { title: "Second title", content: "" },
 { title: "Third title", content: "" }, 
 { title: "Fourth title", content: "Fourth content" } 
 ];
 
 $scope.myListNEW = []; 
 angular.forEach($scope.myListOLD,function(value,key){
 if(value.content !== "")
 $scope.myListNEW.push(value);
 });
 console.log($scope.myListNEW);
 
 });
 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeCtrl">
</div>

You can use this

 angular.forEach($scope.myListOLD,function(value,key){
 if(value.content !== "")
 $scope.myListNEW.push(value);
 });
answered Sep 13, 2016 at 4:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.