2016-09-13 5 views
0

Wenn ich wie so in meinem Rahmen etwas eine Variable haben:AngularJS entfernen Objekte mit leeren Feldern

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

Wie könnte ich einen neuen Bereich Variable erstellen, die keine leeren Werte auf einem bestimmten Feld entfernt? (In diesem Fall Inhalt).

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

Antwort

3

Verwenden 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

Funktioniert wunderbar! Vielen Dank! – 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>

können Sie diese

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