I have the following JSON structure:
{
"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
The final JSON should look like:
{
"id": 123,
"shops": [
{
"shopId": 456,
"products": [
{
"productId": 10001,
"name": "abc",
"state": "active"
}
]
},
{
"shopId": 789,
"products": [
{
"productId": 20002,
"name": "jbf",
"state": "active"
}
]
}
]
}