gpt4 book ai didi

javascript - 在数组中,多个对象需要使用 javascript 将单个对象与总和值合并

转载 作者:行者123 更新时间:2023-11-29 21:32:44 25 4
gpt4 key购买 nike

我有一个包含多个数组对象的数组结果,我需要将结果合并到具有唯一值 content 和 sum total 值的单个数组中> 喜欢下面想要的结果。非常感谢您的帮助

Result Set

[
[
{
content: 'Aqurie',
total: 5
},
{
content: 'Mail function',
total: 4
}
],
[
{
content: 'Aqurie',
total: 4
},
{
content: 'Mail function',
total: 10
}
]
]

Desired Result

[
{
content: 'Aqurie',
total: 9
},
{
content: 'Mail function',
total: 14
}
]

我当前的实现尝试做这样的事情:

var transformed = arr.reduce(function(a, b){ return a.concat(b); });
console.log(transformed );

最佳答案

如果所有嵌套数组中的顺序都相同,则可以使用以下内容

var arr = [
[{
content: 'Aqurie',
total: 5
}, {
content: 'Mail function',
total: 4
}],
[{
content: 'Aqurie',
total: 4
}, {
content: 'Mail function',
total: 10
}]
];

// reduce function for merging the array
var res = arr.reduce(function(a, b) {
// iterating the array for updating total
var ret = a.map(function(v, i) {
v.total += b[i].total;
// returning updated object
return v;
});
// returning merged array
return ret;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


更新 1: 如果顺序是随机的,则在 map() 中添加一个额外的 for 循环,并通过比较 content 属性

检查元素

var arr = [
[{
content: 'Aqurie',
total: 5
}, {
content: 'Mail function',
total: 4
}],
[{
content: 'Mail function',
total: 10
}, {
content: 'Aqurie',
total: 4
}]
];

// reduce method to merge the array
var res = arr.reduce(function(a, b) {
// iterating over inner array and updating total value based on content
var ret = a.map(function(v) {
// for loop for finding matched array index
for (i1 = 0; i1 < b.length; i1++) {
// checking content
if (v.content == b[i1].content) {
// if matched updating the total value
v.total += b[i1].total;
// breking the for loop on match
break;
}
}
// returning updated array
return v;
});
// returning merged array
return ret;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


更新 2:上述方法在某些情况下不起作用,它只更新第一个数组值的总数。例如:- 如果第二个数组包含其他内容,则将跳过。

var arr = [
[{
content: 'Aqurie',
total: 5
}],
[{
content: 'Mail function',
total: 10
}, {
content: 'Aqurie',
total: 4
}],
[{
content: 'other',
total: 4
}]

];

// reduce method to merge the array
var res = arr.reduce(function(a, b) {
// iterating over inner array and updating total value based on content
b.forEach(function(v) {
// for loop for finding matched array index
var found = false;
for (i1 = 0; i1 < a.length; i1++) {
// checking content
if (v.content == a[i1].content) {
found = true;
// if matched updating the total value
a[i1].total += v.total;
// breking the for loop on match
break;
}
}
// pushing element if new element found
if (!found)
a.push(v);
});
return a;
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');


关于javascript - 在数组中,多个对象需要使用 javascript 将单个对象与总和值合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35739922/

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