gpt4 book ai didi

javascript - 以不可变的方式过滤2层数组对象

转载 作者:行者123 更新时间:2023-12-02 22:07:25 24 4
gpt4 key购买 nike

我有一个以下格式的对象数组,旨在以不可变方式进行过滤。可以使用pure javascriptes6lodash 库来完成。

注意:这里的关键点是以不可变方式进行过滤。

逻辑:

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});

关于javascript - 以不可变的方式过滤2层数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com