简体   繁体   English

遍历嵌套的json数组对象并求和JavaScript

[英]Loop through nested json array object and sum values javascript

I would like to create a new object with OrgID, Name and Value with unique OrgID. 我想用OrgID,名称和值创建具有唯一OrgID的新对象。

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"
    }
}

For below example: sum of id 0 and 1 should occur, and 3rd and 4th id as it is. 对于下面的示例:ID 0和1的总和应该出现,第3和第4 ID保持原样。

Final Object = [
{1, A, 94521},
{2, C, 75463},
{3, D, 56743}
];

I tried using nested for loops and reduce. 我尝试使用嵌套的循环和减少。 But I am unable to get results I need. 但是我无法获得所需的结果。

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})
);

try this, is it desired result? 试试这个,是想要的结果吗?

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM