Reputation: 14226
I have a big json object I am using to control a cascading select list that I am trying to filter down to prepare for sending to the server.
The structure looks something like this -
Accounts[{name:account1, id:1, selected:false, schools:[{name:school1, id:2,selected:true}]}]
(With multiple accounts with multiple schools in each, keeping it simple for example purposes)
What I am trying to do is put it through some maps/filters and achieve an array of ids of schools that have the key of selected = true. So my attempt is to filter down by first all schools, then by schools that have selected true, then just the id's of those schools.
So here is my attempt -
$scope.schooIDsForSave = $scope.accountTreeHere.filter( function(obj){
return obj.schools;
}).filter( function(obj){
return obj.selected;
}).map(function(obj){
return obj.id;
});
This is only returning 1 ID so I'm getting something wrong here. I think I have something wrong with my usage of map/filter as I am still vey new to it. Any insight to point me in the right direction would be much appreciated! Thanks for reading.
Upvotes: 0
Views: 79
Reputation: 26873
Given structure
var schools = [{
name: 'account1',
id: 1,
selected: false,
schools: [{
name: 'school1',
id: 2,
selected: true
}]
}, {
name: 'account2',
id: 2,
selected: false,
schools: [{
name: 'school2',
id: 3,
selected: false
}]
}];
Try
var ids = schools.map(function(v) {
return v.schools;
}).reduce(function(a, b) {
return a.concat(b);
}).filter(function(v) {
return v.selected;
}).map(function(v) {
return v.id;
});
Upvotes: 1