Skip to content

Creating an array by nested map with filtering

  const market = [
    {
      id: 0,
      properties: [{ name: 'salad', price: 99, isMain: true }],
      value: "1"
    },
    {
      id: 1,
      properties: [{ name: 'patato', price: 100, isMain: false }],
      value: "2"
    },
    {
      id: 2,
      properties: [{ name: 'strawberry', price: 101, isMain: true }],
      value: "3"
    },
  ];

I have data like above, I want to make list of properties which has isMain property is true like the example below. How can I best do this with ES6?

expectation ==>

  [
    {
      name: 'salad',
      price: 99,
      isMain: true,
    },
    {
      name: 'strawberry',
      price: 101,
      isMain: true,
    },
  ];

Answer

You need to flat the array and then use the filter method to get your desired items from nested array, this will work even if you have multiple items in properties array.

var filtredItems = [];
const market = [
    {
        id: 0,
        properties: [{ name: 'salad', price: 99, isMain: true }],
        value: "1"
    },
    {
        id: 1,
        properties: [{ name: 'patato', price: 100, isMain: false }, { name: 'second', price: 100, isMain: true }],
        value: "2"
    },
    {
         id: 2,
         properties: [{ name: 'strawberry', price: 101, isMain: true }],
         value: "3"
    },
];
filtredItems = market.flatMap(x => x.properties).filter(prop=> prop.isMain);

console.log('filtredItems', filtredItems)