在JavaScript中合并具有相同键的对象 [英] Merge objects with same key in javascript
问题描述
如果我有这样的对象数组,我已经很长时间试图解决这个问题了:
I have been trying to figure this out for a long time, if i have an array of objects like so:
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}
]
我想将所有具有相同键的对象合并到一个对象中,以使它们的时间加在一起:
I want to merge all the objects with the same key together into one object, such that their hours get added up:
预期输出:
my_array = [
Object {Project: A, Hours: 8}
Object {Project: B, Hours: 3}
Object {Project: C, Hours: 14}
]
如何解决此问题?以这种方式格式化数据花了我很长时间,这是最后一步!
How can I approach this issue? It has taken me a long time to get my data formatted in this way, this is the last step!
我的尝试是,我在遍历数组,不确定如何处理对象的合并:
My attempt, I get that I am looping through array, not sure how to deal with the merging of the objects:
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
}
推荐答案
在您的尝试中,您错过了创建新数组的机会
In your attempt, you are missing out on creating a new array
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地图中创建最终的输出数组
Now create the final output array out of uniqueproject map
newArray = Object.keys(uniqueproject).map(function(key){return {Project:key, Hours:uniqueproject[key]}});
这篇关于在JavaScript中合并具有相同键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!