Search code examples
javascriptreactjsarraysobject

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.


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);