gpt4 book ai didi

javascript - 数组需要根据键值对删除重复对象并返回总和 [fiddle]

转载 作者:行者123 更新时间:2023-12-01 16:09:45 29 4
gpt4 key购买 nike

需要根据匹配的键删除重复的对象,但添加值。已经创建了片段和 fiddle 来查看。还在底部添加了预期结果。

我尝试了几种不同的方法,但无法获得预期的结果。我可以使用过滤器方法,但无法为匹配键添加值。请看一下 fiddle 或片段

fiddle link here

  let data2 = [{
area: {
type: "double",
value: 50
},
areaName: {
type: "string",
value: "westside"
},
areaTitle: {
type: "string",
value: "rock"
}
},
{
area: {
type: "double",
value: 250
},
areaName: {
type: "string",
value: "north"
},
areaTitle: {
type: "string",
value: "sand"
}
},
{
area: {
type: "double",
value: 400
},
areaName: {
type: "string",
value: "westside"
},
areaTitle: {
type: "string",
value: "rock"
}
}
];

var filterData2 = Object.keys(data2).reduce((acc, elem) => {
let getKeys = data2[elem];
console.log(getKeys);

return acc;
}, []);

console.log(filterData2);



// Expected result
let result = [{
Area: {
type: "double",
value: 450
},
AreaName: {
type: "string",
value: "westside"
},
AreaTitle: {
type: "string",
value: "rock"
}
},
{
Area: {
type: "double",
value: 250
},
AreaName: {
type: "string",
value: "north"
},
AreaTitle: {
type: "string",
value: "sand"
}
}
]

console.log(result);

最佳答案

使用 reduce & Object.assign()如下所示,您可以获得所需的结果。在代码中添加解释作为注释。

注意 我将 Object.assign 用作 curr = Object.assign({}, x); 而不是 curr = x; 因为 curr = x; 稍后当我们更新 value 并找到现有对象时,它也会更新 value数据2。使用 Object.assign({}, x); 这不会发生。

let data2 = [{
area: {
type: "double",
value: 50
},
areaName: {
type: "string",
value: "westside"
},
areaTitle: {
type: "string",
value: "rock"
}
},
{
area: {
type: "double",
value: 250
},
areaName: {
type: "string",
value: "north"
},
areaTitle: {
type: "string",
value: "sand"
}
},
{
area: {
type: "double",
value: 400
},
areaName: {
type: "string",
value: "westside"
},
areaTitle: {
type: "string",
value: "rock"
}
}
];

// use reduce to iterate over array and produce result
var result = data2.reduce((a, x) => {
// find matching object from a.
let curr = a.filter(y => y.areaName.value == x.areaName.value && y.areaTitle.value == x.areaTitle.value)[0];
// if not exists then create new object and add into a
// else add value to curr.area.value
if (!curr) {
curr = Object.assign({}, x);
a.push(curr);
} else {
curr.area.value += x.area.value;
}
// return a
return a;
}, []);

console.log(result);

关于javascript - 数组需要根据键值对删除重复对象并返回总和 [fiddle],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63501273/

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