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 },
];
CodePudding user response:
You would .filter by isPinned and then .map by name
const namesOfPinnedCountries = countries
.filter(it => it.isPinned)
.map(it => it.name)
CodePudding user response:
.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);
