我想用OrgID,Name和Value创建一个具有唯一OrgID的新对象。
数据:
{
"id":0,
"Value": "12345"
"Organisations"
{
"OrgID": "1",
"Name": "A"
}
},
{
"id":1,
"Value": "74790"
"Organisations"
{
"OrgID": "1",
"Name": "A"
}
}, {
"id":2,
"Value": "89668"
"Organisations"
{
"OrgID": "2",
"Name": "C"
}
},
{
"id":3,
"Value": "23559"
"Organisations"
{
"OrgID": "3",
"Name": "D"
}
}
对于以下示例:应该出现id 0和1的总和,并且原样是第3和第4个id。
Final Object = [
{1, A, 94521},
{2, C, 75463},
{3, D, 56743}
];
我尝试使用嵌套for循环并减少。但是我无法得到我需要的结果。
var result = Array.from(
data.reduce((organisations, obj) =>
organisations.set(obj.organisations.Name,
(organisations.get(obj.organisations.Name) || 0) + +obj.Value),
new Map()),
([organ, sum]) => ({organ,sum})
);
答案 0 :(得分:2)
试试这个,这是期望的结果吗?
var data = [
{
"id":0,
"Value": "12345",
"Organisations":
{
"OrgID": "1",
"Name": "A"
}
},
{
"id":1,
"Value": "74790",
"Organisations":
{
"OrgID": "1",
"Name": "A"
}
}, {
"id":2,
"Value": "89668",
"Organisations":
{
"OrgID": "2",
"Name": "C"
}
},
{
"id":3,
"Value": "23559",
"Organisations":
{
"OrgID": "3",
"Name": "D"
}
}
];
var res = {};
res = Object.keys(data.reduce((res, curr) => {
res[curr.Organisations.OrgID] = res[curr.Organisations.OrgID] || {
OrgID: curr.Organisations.OrgID,
Name: curr.Organisations.Name,
Value: 0
};
res[curr.Organisations.OrgID].Value += parseInt(curr.Value);
return res;
}, res)).map(key => res[key]);
console.log(res);