gpt4 book ai didi

javascript - 如何在javascript中组合具有相同键的数组中的对象?

转载 作者:行者123 更新时间:2023-11-30 06:20:59 25 4
gpt4 key购买 nike

我有一个对象数组,我想根据 javascript 中的公共(public)日期属性减少对象的数量

示例输入:

const data = [
{date:"1 Nov", foo: 123},
{date:"1 Nov", bar: 456},
{date:"2 Nov", foo: 234},
{date:"2 Nov", bar: 567}
];

预期输出

const data = [
{date:"1 Nov", foo: 123, bar: 456},
{date:"2 Nov", foo: 234, bar: 567},
];

最佳答案

也许您可以使用 Array#reduce method 来实现这一点,因为预期的输出是输入数组的聚合。应用此方法的一种方法可能是;

  1. 对于输入数组的每次迭代,检查当前输出数组结果(即如下所示的 result)是否有任何日期与当前 item 匹配的项目>/li>
  2. 如果找到匹配项,则将找到的对象“传播”到具有匹配“日期”的现有对象中(即将两个对象的键/值组合成一个新对象),并将其分配回 结果数组
  3. 否则,如果没有找到匹配项,只需将当前项按原样添加到结果数组

以下代码显示了此描述 - 希望对您有所帮助!

const data = [
{date:"1 Nov", foo: 123},
{date:"1 Nov", bar: 456},
{date:"2 Nov", foo: 234},
{date:"2 Nov", bar: 567}
];

const output = data.reduce((result, item) => {

const i = result.findIndex(resultItem => resultItem.date === item.date)

if(i === -1) {
// No item in current result array found that matches the date of item
// so add item to result array
result.push(item)
}
else {
// An item found with date matching item in current result so combine
// the two into a new object and assign this back into our result
// array
result[i] = { ...result[i], ...item }
}

return result
}, [])

console.log(output);

关于javascript - 如何在javascript中组合具有相同键的数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138769/

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