Home > Net >  find in array of objects with nested array of objects with multiple property name and value
find in array of objects with nested array of objects with multiple property name and value

Time:12-29

I have Array of objects like this

[{
    property1: 'test',
    property2: 'test',
    filter: [{
        fil1: 1,
        fil2: 2,
        fil3: 3
      },
      {
        fil1: 56,
        fil2: 3,
        fil3: 34
      },
      {
        fil1: 23,
        fil2: 88,
        fil3: 6
      }
    ]
  },
  {
    property1: 'test2',
    property2: 'test2',
    filter: [{
        fil1: 44,
        fil2: 5,
        fil3: 99
      },
      {
        fil1: 333,
        fil2: 7,
        fil3: 888
      },
      {
        fil1: 10,
        fil2: 5,
        fil3: 688
      }
    ]
  }
]

as you can see i have two objects. each object have nested array with objects. i want to get main object if i search for some properties inside nested array of objects.

for example fil1: 56, fil2:3 , i need to get first main object in first match. but there is trick. property names inside nested objects are dynamic and i need to search sometimes by one property or 5 property. i have search object like this

{
  fil2: 2,
  fil3: 3
}

entering this searching object will return first main object in array.

CodePudding user response:

data.find((el) => el.filter.some((el_n) => !Object.entries(search).some(([key, value]) => el_n[key] != value)));

where data is searchable array of objects and search is search object. This will return the first matching object from data.

This will work for any number of keys inside filter array element or in search object.

eg:

{
    fil1: 5,
    fil2: 5,
    fil3: 686,
    fil4: 686,
    search_by_this_key: 34,
    ...
}

Filtering arrays client side on a large data set can impact performance, in that case you might want to look into a backend solution.

CodePudding user response:

  • Related