Loop through nested json array object and sum values javascript -


i create new object orgid, name , value 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 , 1 should occur, , 3rd , 4th id is.

final object = [ {1, a, 94521}, {2, c, 75463}, {3, d, 56743} ]; 

i tried using nested loops , reduce. unable results 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, 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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -