I have this array of objects with the name
and isPinned
keys. I would like to store only the country name in a new array based on what isPinned
is. For example, if Australia and China have isPinned
as true, then the new array would be:
const countriesFiltered = ["Australia", "China"]
const countries = [
{ name: "Australia", isPinned: true },
{ name: "China", isPinned: true },
{ name: "India", isPinned: false },
];
You would .filter
by isPinned
and then .map
by name
const namesOfPinnedCountries = countries
.filter(it => it.isPinned)
.map(it => it.name)
.filter()
and .map()
is the classical solution, but you can also do it with .reduce()
:
const countries = [ { name: "Australia", isPinned: true }, { name: "China", isPinned: true }, { name: "India", isPinned: false }, ]; const res=countries.reduce((a,c)=> c.isPinned?[...a,c.name]:a,[]); console.log(res);
You can use flatMap :
const countries = [ { name: "Australia", isPinned: true }, { name: "China", isPinned: true }, { name: "India", isPinned: false }, ]; const countriesFiltered = countries.flatMap(i => i.isPinned? i.name: []); console.log(countriesFiltered);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.