I have a array of objects like this
let input = [
{
"metadata": { "id": 1071, "name": "USA" },
"accesories": [ { "name": "steel" } ]
},
{
"metadata": { "id": 1068, "name": "China" },
"accesories": [ { "name": "electronics" } ]
},
]
Desired output:
["USA", "China"]
In order to get above result, I use the following
input.map((el) => el?.metadata?.name);
But if I want to filter first by electronics
and based on which object has accessories with name as electronics
in it, how do I achieve that result?
for e.g.
output: ["USA"] //if I want to filter by object which has name steel
output: ["China"] //if I want to filter by object which has name electronics
Can someone let me know how can I use filter with above map method?
2
Answers
You can do this by first filtering the array based on the presence of the desired accessory name, and then mapping over the filtered array to extract the names like this.
Use the filter() method to create an array with only the desired accessory.
Use the map() method to extract the name
If you need a performant solution, avoid intermediate arrays and use
Array#reduce()
:And a benchmark: