gpt4 book ai didi

javascript - 使用相同的键(日期)组合数组中的对象

转载 作者:行者123 更新时间:2023-11-30 21:15:13 25 4
gpt4 key购买 nike

我有一个对象数组,我想组合具有相同日期值的对象,所以我有一个类似的数组。我正在使用 .map(i => ) 遍历它们并检查之前的索引,但我得到了错误的值。

 [{ id: '8',
name: 'hfh',
consumed_date: '2017-03-14',
calories: 8952 },
{ id: '7',
name: 'onion',
consumed_date: '2017-03-14',
calories: 224},
{ id: '6',
name: 'onion',
consumed_date: '2017-03-14',
calories: 279},
{ id: '2',
name: 'Ready-to-Serve Chocolate Drink',
consumed_date: '2017-01-01',
calories: 3036} ]

我想以这样的数组结束

[{date: 2017-03-14,
calories: 9455},
date: 2017-01-01,
calories: 3036}]

最佳答案

Reduce 非常适合这样的情况:我们需要“循环”遍历所有项目,但我们不希望出现类似“a => modify(a)”的直接行为map,而是需要将几个值减少或折叠成其他东西(在这种情况下,输入和输出都是一个数组,但一些值被减少为一个)。

当我们遍历所有项目时,我们需要一些变量来保存状态(到目前为止的进度)。在一种更命令的风格中,将通过在 for 循环之外声明的变量来解决,但在 reduce 中,“到目前为止的进度”-变量 (acc) 被传递随着每次迭代,以及下一个项目。

const reducedArray = arr.reduce((acc, next) => { // acc stands for accumulator
const lastItemIndex = acc.length -1;
const accHasContent = acc.length >= 1;

if(accHasContent && acc[lastItemIndex].consumed_date == next.consumed_date) {
acc[lastItemIndex].calories += next.calories;
} else {
// first time seeing this entry. add it!
acc[lastItemIndex +1] = next;
}
return acc;
}, []);

console.log(reducedArray)

(此解决方案假定数据按日期排序。)

关于javascript - 使用相同的键(日期)组合数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746622/

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