0

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.

3
  • Just use some (i.e., return entry.secondaryObjects.some((so) => so.second2Name.includes("hello"));) Commented Nov 29, 2022 at 20:22
  • If you think about it, this is just a multi-step filter. You use some because you don't care about the array being returned from the inner filter, rather you just care that it isn't empty and can therefore stop looking sooner. Commented Nov 29, 2022 at 20:25
  • I see so does I was trying to .map through it and wasnt understanding why it was working but that makes more sense now! didnt realise .some was a function Commented Nov 29, 2022 at 20:29

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to look into all secondary objects then. Some will do that for you:

const filteredField = 
  data.filter(entry => entry.secondaryObjects
    .some(o => o.second2Name.includes('hello'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.