Murlidhar Fichadia Murlidhar Fichadia - 1 month ago 15
Javascript Question

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.

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.

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

Answer

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

Comments