Home > Back-end >  How to filter array of objects with two-level nesting?
How to filter array of objects with two-level nesting?

Time:10-01

I'm have a problem with filtering array of objects with two-levels nesting.

I have 2 arrays, first array is one-level nesting and I have code which work well with it.

const storyId = 2

const arrayOne = [
      {
        name: 'First',
        storyId: 1,
      },
      {
        name: 'Second',
        storyId: 2,
      },
      {
        name: 'Third',
        storyId: 3,
      }
    ]

const result = arrayOne.filter(el => el.storyId === storyId)

But in my case I need to filter array by value of second level of nesting. So I have a next code:

const storyId = 5

let arrayTwo = [
      {
        name: 'First',
        id: 1,
        libraries: {
          nodes: [
            {storyId: 1},
            {storyId: 3},
            {storyId: 5},
          ]
        }
      },
      {
        name: 'Second',
        id: 2,
        libraries: {
          nodes: [
            {storyId: 4},
            {storyId: 5},
            {storyId: 6},
          ]
        }
      },
      {
        name: 'Third',
        id: 3,
        libraries: {
          nodes: [
            {storyId: 3},
            {storyId: 2},
            {storyId: 1},
          ]
        }
      }
    ]

And here I'm expect got array of all first-level objects which have inside libraries->nodes storyId: 5

Tell me please how i can filter it. Preferably in one line

CodePudding user response:

Not necessarily the most performant way, but this will get only elements with nodes that have a matching storyId

arrayTwo.filter(el => el.libraries.nodes.filter(n => n.storyId === storyId).length > 0)))
  • Related