Reputation: 297
My JSON array of objects is:
[{
"stateCd": "IL",
"value": "Illinois",
"selected": "false"
},
{
"stateCd": "CA",
"value": "California",
"selected": "true"
},
{
"stateCd": "NY",
"value": "New york",
"selected": "false"
}]
I want to create a new JSON array of objects which should only contain those objects from above array where selected:false
.
I've tried concat
:
angular.forEach($scope.oldJsonArr, function (value, index) {
if($scope.oldJsonArr[index].selected=="false"){
$scope.newJsonArr.concat($scope.oldJsonArr[index]);
}
});
But this is returning the newJsonArr
as undefined.
Any help is appreciated!
Upvotes: 0
Views: 113
Reputation: 7746
Use Filter
from JavaScript
rather using library utility function.
var people = [
{ firstname:"Micro", hasSocialNetworkSite: false, lastname:"Soft", site:"http://microsoft.com" },
{ firstname:"Face", hasSocialNetworkSite: true, lastname:"Book", site:"http://facebook.com" },
{ firstname:"Go", hasSocialNetworkSite: true, lastname:"ogle", site:"http://google.com" },
{ firstname:"Twit", hasSocialNetworkSite: true, lastname:"Ter", site:"http://twitter.com" },
{ firstname:"App", hasSocialNetworkSite: false, lastname:"Le", site:"http://apple.com" },
{ firstname:"Master", hasSocialNetworkSite: false, lastname:"Card", site:"http://mastercard.com" }
];
var filteredResult = people.filter(function(v) {
return v.hasSocialNetworkSite == true; // Filter out the appropriate one
});
document.write("Social Networking Site<br>");
for (var i in filteredResult) {
document.write(filteredResult[i].site + "<br>")
}
Reference to know in detail:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://msdn.microsoft.com/en-us/library/ff679973(v=vs.94).aspx
http://www.w3schools.com/jsref/jsref_filter.asp
Upvotes: 0
Reputation: 1200
You can use Array.prototype.filter() method.
var falseFilter = function(value) {
return value.selected == "false";
};
var newJsonArray = oldJsonArray.filter(falseFilter);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Upvotes: 0
Reputation: 8079
Here is the code:
$scope.oldJsonArr = [{"stateCd": "IL", "value": "Illinois", "selected": "false"}, {
"stateCd": "CA",
"value": "California",
"selected": "true"
}, {"stateCd": "NY", "value": "New york", "selected": "false"}];
$scope.newJsonArr = [];
angular.forEach($scope.oldJsonArr, function (value, index) {
if ($scope.oldJsonArr[index].selected == "false") {
$scope.newJsonArr.push($scope.oldJsonArr[index]);
}
});
console.info($scope.newJsonArr);
undefined
.push()
methodUpvotes: 2