Reputation: 1277
I would like to reduce an array of objects to a string array based on a boolean property.
My object array looks like that:
diet: [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
My ideal outcome would be a string array if the selected value is true.
["dairy-free", "poultry", "vegetarian"]
Upvotes: 1
Views: 185
Reputation: 3305
another way could be
final newList = diet.fold<List>([], (previousValue, e) {
if (e["selected"]) {
previousValue.add(e["slug"]);
}
return previousValue;
});
Upvotes: 0
Reputation: 774
Something like this using a combination of Array
functions filter
and map
:
let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
let selected=diet.filter(type=>type.selected).map(selectedType=>selectedType.slug)
console.log(selected)
This unfortunately requires two iterations over an array, once to filter out the selected
and once to return only the slug
You can also achieve the same result using reduce
like this
let diet= [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
let reduced = diet.reduce((filtered, option)=> {
if (option.selected) {
filtered.push(option.slug);
}
return filtered;
}, []);
console.log(reduced)
reduce
would be the recommended approach since you only iterate once over the array
Upvotes: 1
Reputation: 15187
You only need filter
and map
.
Using filter
you will get those whose value selected
is true. And map
is for mapping slug
value for these objects into an array.
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
var newArray = diet.filter(f => f.selected).map(m => m.slug)
console.log(newArray)
Upvotes: 2
Reputation: 751
You can use filter
method to filter the records which have selected value as true. This will return an array of objects that satisfy the condition
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
console.log(diet.filter(e => e.selected))
If you want to return only the slug property, you can use filter
and map
methods combined
var diet = [ { slug: "dairy-free", selected: true, }, { slug: "fish", selected: false, }, { slug: "meat", selected: false, }, { slug: "poultry", selected: true, }, { slug: "vegetarian", selected: true, }, ]
console.log(diet.filter(e => e.selected == true).map(e => e.slug))
Upvotes: 2