我在过滤带有嵌套对象的数组时遇到问题。
[{
"firstName": "Kevin",
"lastName": "Smith",
"expenses": {
"drink1": 25,
"drink2": 20
}
},
{
"firstName": "John",
"lastName": "Rambo",
"expenses": {
"coffe": 10,
"cake": 20
}
}
]
我想获取所有费用之和大于35的对象。如何获得
expenses
呢?也许在这里过滤不是正确的方法。 最佳答案
只需使用filter
对其进行编码,条件是使用reduce
来汇总费用!非常简单:)
const input = [{
"firstName": "Kevin",
"lastName": "Smith",
"expenses": {
"drink1": 26,
"drink2": 20
}
},
{
"firstName": "John",
"lastName": "Rambo",
"expenses": {
"coffe": 10,
"cake": 20
}
}
];
const output = input.filter(user => Object.values(user.expenses).reduce((acc, expense) => acc + expense) > 45);
console.log(output);