gpt4 book ai didi

javascript - 合并不同长度的对象

转载 作者:行者123 更新时间:2023-11-30 21:08:57 24 4
gpt4 key购买 nike

我有一个对象数组,以日期字符串为键,布局如下:

[
{
'2017-08-21': {row: 0, artind: 25, qind: 20},
'2017-08-22': {row: 1, artind: 5, qind: 12},
'2017-08-23': {row: 11, artind: 3, qind: 0},
'2017-08-24': {row: 45, artind: 25, qind: 43},
'2017-08-25': {row: 13, artind: 0, qind: 27},
'2017-08-26': {row: 2, artind: 2, qind: 2},
'2017-08-27': {row: 1, artind: 12, qind: 27},
'2017-08-28': {row: 19, artind: 0, qind: 0},
'2017-08-29': {row: 11, artind: 25, qind: 7}
},
{
'2017-08-24': {row: 1, artind: 34, qind: 8},
'2017-08-25': {row: 0, artind: 5, qind: 3},
'2017-08-26': {row: 7, artind: 22, qind: 0}
},
{
'2017-08-22': {row: 55, artind: 5, qind: 2},
'2017-08-23': {row: 13, artind: 25, qind: 0},
'2017-08-24': {row: 1, artind: 0, qind: 0},
'2017-08-25': {row: 6, artind: 8, qind: 0},
'2017-08-26': {row: 0, artind: 12, qind: 89},
'2017-08-27': {row: 11, artind: 29, qind: 5}
}
]

我需要对每个对象中的所有值求和。所以最后,我需要一个看起来像这样的对象:

{
'2017-08-21': {row: 0, artind: 25, qind: 20},
'2017-08-22': {row: 56, artind: 10, qind: 14},
'2017-08-23': {row: 24, artind: 28, qind: 0},
'2017-08-24': {row: 47, artind: 59, qind: 51},
'2017-08-25': {row: 19, artind: 13, qind: 30},
'2017-08-26': {row: 9, artind: 36, qind: 91},
'2017-08-27': {row: 12, artind: 41, qind: 32},
'2017-08-28': {row: 19, artind: 0, qind: 0},
'2017-08-29': {row: 11, artind: 25, qind: 7}
}

我真正用于支持的唯一库是 underscore.js,所以非常感谢这些答案!

谢谢

最佳答案

您可以使用下面的 reduce 方法来解决您的问题。

const a = [{
'2017-08-21': { row: 0, artind: 25, qind: 20 },
'2017-08-22': { row: 1, artind: 5, qind: 12 },
'2017-08-23': { row: 11, artind: 3, qind: 0 },
'2017-08-24': { row: 45, artind: 25, qind: 43 },
'2017-08-25': { row: 13, artind: 0, qind: 27 },
'2017-08-26': { row: 2, artind: 2, qind: 2 },
'2017-08-27': { row: 1, artind: 12, qind: 27 },
'2017-08-28': { row: 19, artind: 0, qind: 0 },
'2017-08-29': { row: 11, artind: 25, qind: 7 }
},
{
'2017-08-24': { row: 1, artind: 34, qind: 8 },
'2017-08-25': { row: 0, artind: 5, qind: 3 },
'2017-08-26': { row: 7, artind: 22, qind: 0 }
},
{
'2017-08-22': { row: 55, artind: 5, qind: 2 },
'2017-08-23': { row: 13, artind: 25, qind: 0 },
'2017-08-24': { row: 1, artind: 0, qind: 0 },
'2017-08-25': { row: 6, artind: 8, qind: 0 },
'2017-08-26': { row: 0, artind: 12, qind: 89 },
'2017-08-27': { row: 11, artind: 29, qind: 5 }
}];

a.reduce((result, item) => {
Object.keys(item).forEach((key) => {
if (result[key]) {
result[key] = {
row: result[key].row + item[key].row,
artind: result[key].artind + item[key].artind,
qind: result[key].qind + item[key].qind };
} else {
result[key] = item[key];
}
});
return result;
}, {});

编辑:只是格式化

关于javascript - 合并不同长度的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46330086/

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