0
  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,
    },
  ];

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

Use ES6 map then filter

  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"
    },
  ];
  
  const results = market.map(product => product.properties[0]).filter(p => !!p.isMain);
  
  console.log(results);

NB: it is quite weird to have a single hash in an array.

Comments

0

you can bind filter with map to get somthing like this i don't know if you have multiple values in properties field:

market.filter(m => m.properties?.[0].isMain)
    .map( m => ({ name: m.name, price: m.properties?.[0].isMain, isMain: m.properties?.[0].isMain  }))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.