Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array of objects and get only those whose property matches with the object in the array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading