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" }
];
2 Answers 2
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
Phil
166k25 gold badges265 silver badges269 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Buster
Works beautifully! Thanks!
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
Hadi
17.3k4 gold badges41 silver badges63 bronze badges
Comments
lang-js