Reputation: 51
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,
},
];
Upvotes: 0
Views: 235
Reputation: 963
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)
Upvotes: 2
Reputation: 31
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 }))
Upvotes: 0
Reputation: 161
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.
Upvotes: 2