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

JavaScript Array Filtering in Nested Arrays

I have an array that looks something like this:

const arrayObj = [
    {
        id: 1,
        itemsList: [
            {
                name: "Paul",
            },
            {
                name: "Newman",
            },
        ],
    },
    {
        id: 2,
        itemsList: [
            {
                name: "Jack",
            },
            {
                name: "Man",
            },
        ],
    },
]

What I want is to filter the objects whose itemsList contain an object with the name of a certain value. For example, I want to be able to filter out an array with objects whose inner objects with names that contain "ul" (in this case the name Paul contains "ul"), it should give me an output as such:

const outputArray = [
    {
        id: 1,
        itemsList: [
            {
                name: "Paul",
            },
            {
                name: "Newman",
            },
        ]
    }
]

So far, I’ve only been able to filter out a simple flat array of objects with this function:

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

function filterByName(array: any, string: any) {
    return array.filter((obj: any) =>
      ["name"].some((key: any) =>
        String(obj[key]).toLowerCase().includes(string.toLowerCase())
      )
    );
}

but I don’t know how to apply it to my case.

>Solution :

Here you can use the some method combined with the includes method

const arrayObj = [{
    id: 1,
    itemsList: [{
        name: "Paul",
      },
      {
        name: "Newman",
      },
    ],
  },
  {
    id: 2,
    itemsList: [{
        name: "Jack",
      },
      {
        name: "Man",
      },
    ],
  },
]


const getFilterArray = (name) => {
  return arrayObj.filter(obj => obj.itemsList.some(x => x.name.toLowerCase().includes(name.toLowerCase())))
}

console.log(getFilterArray("ul"))
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