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

How to filter a JavaScript object based on child object

I have an array of objects with an array that contains other objects. I’m trying to work out how I can filter the first objects based on data inside the array of second objects

[{
   object1Name: "test",
   secondaryObjects: [
    {
       second2Name: "test-again"
       data: "hello"
    },
    {
       second2Name: "Hello!"
       data: "remove based on this"
    }
   ]
},
{
  another object...
}]

I want to filter the first array by checking if any objects contain a secondary object with the data "hello". If they have a secondary object with that data it then filters out the object1

const filteredField = data.filter((entry) => {
            return entry.secondaryObjects[0].second2Name.includes('hello')
        })

When I use this, I have it working but it only checks the first index of secondary objects but if it’s in index 1 it does not work.

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

>Solution :

You were close, you just need to check any inner object contains your desire data by using .some()

const data = [{ object1Name: "test", secondaryObjects: [{ second2Name: "Hello!", data: "remove based on this" }, { second2Name: "hello", data: "hello" } ] }, { object1Name: "test", secondaryObjects: [{ second2Name: "test-again", data: "test...." }] } ];
const filtered = data.filter(item => item.secondaryObjects.some(it => it.second2Name === "hello"));
console.log(filtered);
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