[英]Remove objects from nested array using Lodash
I have the following JSON structure:我有以下 JSON 结构:
{
"id": 123,
"shops": [
{
"shopId": 456,
"products": [
{
"productId": 10001,
"name": "abc",
"state": "active"
},
{
"productId": 10002,
"name": "def",
"state": "expired"
}
]
},
{
"shopId": 789,
"products": [
{
"productId": 20001,
"name": "qrt",
"state": "expired"
},
{
"productId": 20002,
"name": "jbf",
"state": "active"
}
]
}
]
}
I want to remove all products from each shop where the product does not have certain properties.我想从每个商店中删除产品不具有某些属性的所有产品。
If I covert it to a flat map then I can do it fine, but then I lose the outer object as I just have an array with all the products that haven't been removed in.如果我将它转换为平面地图,那么我可以做得很好,但是我丢失了外部对象,因为我只有一个包含所有尚未删除的产品的数组。
_(shopJson.shops).map('products').flatten().map(x => {if(x.state === 'active'){return x}}).compact().value()
I tried the following but just end up with an empty array:我尝试了以下操作,但最终得到了一个空数组:
_(shopJson.shops).map('products').filter(x => x.state === 'active').value()
I also tried using _.reduce()
and _.transform()
but can't get it to work我也尝试使用
_.reduce()
和_.transform()
但无法让它工作
The final JSON should look like:最终的 JSON 应如下所示:
{
"id": 123,
"shops": [
{
"shopId": 456,
"products": [
{
"productId": 10001,
"name": "abc",
"state": "active"
}
]
},
{
"shopId": 789,
"products": [
{
"productId": 20002,
"name": "jbf",
"state": "active"
}
]
}
]
}
You don't really need lodash for this.为此,您实际上并不需要 lodash。 You can just use
Array.prototype.map
and Array.protype.filter
(and also some spread syntax
to shallow merge object properties):你可以只使用
Array.prototype.map
和Array.protype.filter
(还有一些spread syntax
来浅合并对象属性):
const data = {id:123,shops:[{shopId:456,products:[{productId:10001,name:"abc",state:"active"},{productId:10002,name:"def",state:"expired"}]},{shopId:789,products:[{productId:20001,name:"qrt",state:"expired"},{productId:20002,name:"jbf",state:"active"}]}]}; const result = { ...data, shops: data.shops.map((shop) => ({ ...shop, products: shop.products.filter((product) => product.state === 'active'), })), }; console.log(result);
EDIT: As @Deykun pointed out , if you want to ignore shops that don't have any active products, you can filter shops out using Array.prototype.some
in a filter
:编辑: 作为@Deykun指出,如果你想忽略不具有任何活跃产品的商店,你可以过滤出店使用
Array.prototype.some
在一个filter
:
const data = {id:123,shops:[{shopId:456,products:[{productId:10001,name:"abc",state:"active"},{productId:10002,name:"def",state:"expired"}]},{shopId:789,products:[{productId:20001,name:"qrt",state:"expired"},{productId:20002,name:"jbf",state:"expired"}]}]}; const result = { ...data, shops: data.shops .filter((shop) => shop.products.some((product) => product.state === 'active')) .map((shop) => ({ ...shop, products: shop.products.filter((product) => product.state === 'active') })) }; console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.