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?
>Solution :
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
let input = [
{
"metadata": { "id": 1071, "name": "USA" },
"accesories": [ { "name": "steel" } ]
},
{
"metadata": { "id": 1068, "name": "China" },
"accesories": [ { "name": "electronics" } ]
},
];
const filterParameter = "electronics";
const filteredObjects = input.filter(el => el?.accesories.some(acc => acc?.name === filterParameter));
const result = filteredObjects.map(el => el?.metadata?.name);
console.log(result);