Using array map to filter results with if conditional
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter
+ .map
.
$scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
if(obj.selected === true){
ids.push(obj.id);
}
return ids;
}, []);
Just for the sake of clarity, here's the sample .reduce
I used in the JSPerf test:
var things = [
{id: 1, selected: true},
{id: 2, selected: true},
{id: 3, selected: true},
{id: 4, selected: true},
{id: 5, selected: false},
{id: 6, selected: true},
{id: 7, selected: false},
{id: 8, selected: true},
{id: 9, selected: false},
{id: 10, selected: true},
];
var ids = things.reduce((ids, thing) => {
if (thing.selected) {
ids.push(thing.id);
}
return ids;
}, []);
console.log(ids)
EDIT 1
Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox
You're looking for the .filter()
function:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
});
That'll produce an array that contains only those objects whose "selected" property is true
(or truthy).
edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
}).map(function(obj) { return obj.id; });
Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck()
function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.