Buster Buster - 2 months ago 9
AngularJS Question

Angularjs Remove Objects With Empty Fields

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" }
];

Answer

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);