如果我有一个像这样的对象数组,我一直试图弄清楚这个:
var my_array = [
Object {Project: A, Hours: 2},
Object {Project: B, Hours: 3},
Object {Project: C, Hours: 5},
Object {Project: A, Hours: 6},
Object {Project: C, Hours: 9}
]
我想将具有相同键的所有对象合并到一个对象中,以便将它们的小时数相加:
预期产出:
my_array = [
Object {Project: A, Hours: 8}
Object {Project: B, Hours: 3}
Object {Project: C, Hours: 14}
]
我该如何处理这个问题?我花了很长时间才能以这种方式格式化我的数据,这是最后一步!
我的尝试,我知道我在循环数组,不知道如何处理对象的合并:
for (var i =0; i<my_array.length; i++) {
my_array[i].Project // access the object project key
my_array[i].Hours // need to increment hours
}
答案 0 :(得分:7)
您可以创建另一个对象,您可以在其中实际对项目进行分组并累积相应的小时数,例如
var groups = my_array.reduce(function(resultObject, currentObject) {
// if this is the first time the project appears in the array, use zero as the
// default hours
resultObject[currentObject.Project] = resultObject[currentObject.Project] || 0;
// add the current hours corresponding to the project
resultObject[currentObject.Project] += currentObject.Hours;
return resultObject;
}, {});
此时,您的groups
将如下所示
console.log(groups);
// { A: 8, B: 3, C: 14 }
现在,您只需要扩展此对象,就像这样
var result = Object.keys(groups).map(function(currentGroup) {
return {Project: currentGroup, Hours: groups[currentGroup]};
});
现在,结果将是
[ { Project: 'A', Hours: 8 },
{ Project: 'B', Hours: 3 },
{ Project: 'C', Hours: 14 } ]
答案 1 :(得分:2)
在您的尝试中,您错过了创建新数组
var newArray = [];
var uniqueprojects = {};
for (var i =0; i<my_array.length; i++) {
if ( !uniqueproject[my_array[i].Project] )
{
uniqueproject[my_array[i].Project] = 0;
}
uniqueproject[my_array[i].Project] += my_array[i].Hours;
//my_array[i].Project // access the object project key
//my_array[i].Hours // need to increment hours
}
现在用uniqueproject map
创建最终输出数组newArray = Object.keys(uniqueproject).map(function(key){return {Project:key, Hours:uniqueproject[key]}});
答案 2 :(得分:2)