2016-09-13 97 views
0

如果我有我的事情的範圍內,像這樣的變量:Angularjs刪除對象帶有空字段

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

我怎麼可以創建取消了對特定字段中的任何空值的新範圍變量? (在這裏是內容)。

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

回答

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

+0

精美的作品!謝謝! – Buster

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>

您可以使用此

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