Reputation: 41
I have an array object that look like this:
[{
sellerId: "seller1",
name: "Nike",
item: [{
id: "xxx1"
isChecked: false
price: "719700.00"
productName: "product a"
quantity: 2
},
{
id: "xxx2"
isChecked: true
price: "219700.00"
productName: "product b"
quantity: 1
}
],
},
{
sellerId: "seller2",
name: "Adidas",
item: [{
id: "xxx1"
isChecked: false
price: "49700.00"
productName: "product x"
quantity: 1
},
{
id: "xxx2"
isChecked: true
price: "4700.00"
productName: "product y"
quantity: 5
}
],
},
]
now I want to convert or filter my data by isChecked = true on object called Item, so it will look like this:
[{
sellerId: "seller1",
name: "Nike",
item: [
{
id: "xxx2"
isChecked: true
price: "219700.00"
productName: "product b"
quantity: 1
}
],
},
{
sellerId: "seller2",
name: "Adidas",
item: [
{
id: "xxx2"
isChecked: true
price: "4700.00"
productName: "product y"
quantity: 5
}
],
},
]
EDITED:
And then IF there is NO isChecked: true in one seller, it will not display the seller data, for example if there is no isChecked on Adidas seller, i expected the object will look like this:
[{
sellerId: "seller1",
name: "Nike",
item: [
{
id: "xxx2"
isChecked: true
price: "219700.00"
productName: "product b"
quantity: 1
}
],
},
]
I have try using lodash like this, but it still not remove the item that have isChecked: false
_.filter(data, { item: [{ isChecked: false }] })
Any help on how I can do that with lodash or simple javascript filter()?
Thank you!
Upvotes: 0
Views: 1422
Reputation: 69
You can use filter and map functions:
sellers = data.map((d) => {return {...d, item: d.item.filter(i=>i.isChecked)}})
For empty items you can filter it again like this:
filterd_seller = sellers.filter(seller => seller.item.length)
Or a better answer you can use reduce:
data.reduce((filtered, seller) => {
const item = seller.item.filter(i => i.isChecked);
if (item.length) {
filtered.push({...seller, item });
}
return filtered;
}, []);
Upvotes: 1
Reputation: 191996
Map the array of objects (using lodash or vanilla), and then recreated the object while filtering out any item with isChecked: false
:
const arr = [{"sellerId":"seller1","name":"Nike","item":[{"id":"xxx1","isChecked":false,"price":"719700.00","productName":"product a","quantity":2},{"id":"xxx2","isChecked":true,"price":"219700.00","productName":"product b","quantity":1}]},{"sellerId":"seller2","name":"Adidas","item":[{"id":"xxx1","isChecked":false,"price":"49700.00","productName":"product x","quantity":1},{"id":"xxx2","isChecked":true,"price":"4700.00","productName":"product y","quantity":5}]}]
const result = arr.map(({ item, ...o }) => ({
...o,
item: item.filter(o => o.isChecked)
}))
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0