我有一个以下格式的对象数组,旨在过滤immutable way
.可以使用pure javascript
、es6
或lodash
库来完成。
注意:这里的关键点是immutable way
中的过滤器。
逻辑:
if (all product qty in the first level object is empty string or 0) {
do not show that first that level object
}
if (product qty is empty string or 0) {
do not show that product
}
输入:
let targetArray = [{
recipient: '1',
product: [{
productId: '1',
qty: '2'
}, {
productId: '2',
qty: '0'
}
]
}, {
recipient: '2',
product: [{
productId: '1',
qty: '0'
}, {
productId: '3',
qty: ''
}
]
},
]
预期产出:
[
{
recipient: '1',
product: [{
productId: '1',
qty: '2'
}]
}
]
我会为此使用 reduce
let targetArray = [
{
recipient: '1',
product: [{
productId: '1',
qty: '2'
}, {
productId: '2',
qty: '0'
}]
},
{
recipient: '2',
product: [{
productId: '1',
qty: '0'
}, {
productId: '3',
qty: ''
}]
},
]
let filtered = targetArray.reduce((acc,curr) => {
let products = curr.product.filter(product => parseInt(product.qty) > 0);
if (products.length === 0) {
return acc;
}
acc.push({...curr, product: products});
return acc;
}, [])
console.log({filtered});
console.log({targetArray});