Home > Software engineering >  Filter Array of objects with nested array
Filter Array of objects with nested array

Time:02-19

so I am trying to set up a nested filter on an array of objects. The thing is that the filter is applied inside the object on a key that is another array of objects.

here is the code:

const items = [
  { name: "123", id: 1, value:  true, arr: [{ id: 1 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 2 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 3 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 4 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 5 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];

const newArray = items.filter((objects) => {
  objects.arr.filter((item) => {
    if (item.id === 2) {
      return objects;
    }
     
  });
});
console.log(newArray);

I 'm not sure where to put the return because in this situation i just get an empty array.

CodePudding user response:

You need to check the nested array contains the wanted id and return the result to the filter method.

const
    items = [{ name: "123", id: 1, value: true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] }],
    result = items.filter(({ arr }) => arr.some(({ id }) => id === 2));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Use Array#some to check if current arr has an element with id equal to 2:

const items = [ { name: "123", id: 1, value:  true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] } ];

const newArray = items.filter(({ arr = [] }) => 
  arr.some(({ id }) => id === 2)
);

console.log(newArray);

  • Related