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

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

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

Comments

Your Answer

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.