Angularjs删除空字段对象

时间:2016-09-13 04:42:57

标签: javascript angularjs arrays

如果我在我的范围内有一个像这样的变量:

<a href="tyreDetails.php?id=<?php echo $product["recid"]; ?>">

如何创建一个删除特定字段上任何空值的新范围变量? (在这种情况下是内容)。

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

&#13;
&#13;
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);
  
    });
    
    
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app" ng-controller="homeCtrl">

</div>
&#13;
&#13;
&#13;

您可以使用此

 angular.forEach($scope.myListOLD,function(value,key){
    if(value.content !== "")
      $scope.myListNEW.push(value);
  });