mfa26
mfa26

Reputation: 33

What is the best way to filter an array of object inside another array of objects?

I have an array like that:

     const array = [
       { 
         id: 1,
         list: [
          {
            name: "abc",
            quantity: 46,
          },
          {
            name: "abc cba",
            quantity: 8,
          },
         ]
       }
    
       { 
         id: 2,
         list: [
          {
            name: "def",
            quantity: 895,
          },
          {
            name: "abc ebn",
            quantity: 8,
          },
         ]
       }
     ]

What would be the best way to filter this array, if I want to check if the array contains: name: "abc" and filter only the objects containing this?

i've tried to use map.() inside filter(), but i don't know if it's a proper way to do this. My code is something like this:

let filteredArray = array.filter(el => {

   let filteredName;

   el.list.map (name => {
      if (elt.name.includes("abc"){
        filteredName = name
       }
   }
 return filteredName;
})

Upvotes: 3

Views: 306

Answers (2)

Barmar
Barmar

Reputation: 782105

You should be using filter() inside map(), so you can filter the list arrays.

You can use flatMap() to get all the objects into a single array rather than nested arrays.

const array = [{
    id: 1,
    list: [{
        name: "abc",
        quantity: 46,
      },
      {
        name: "abc cba",
        quantity: 8,
      },
    ]
  },
  {
    id: 2,
    list: [{
        name: "def",
        quantity: 895,
      },
      {
        name: "abc ebn",
        quantity: 8,
      },
    ]
  }
];

let filteredArray = array.flatMap(obj => obj.list.filter(el => el.name.includes("abc")));
console.log(filteredArray);

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28424

const array = [
  { id: 1, list: [ { name: "abc", quantity: 46, }, { name: "abc cba", quantity: 8 } ] },
  { id: 2, list: [ { name: "def", quantity: 895, }, {  name: "abc ebn", quantity: 8 } ] }
];

// iterate over array
const res = array.map(({ list, ...el }) => (
  // filter current element's list
  { ...el, list: list.filter(({ name }) => name.includes("abc")) }
));

console.log(res);

Upvotes: 2

Related Questions