javascript - Groupby without using underscore js -


i have collection group id. each id contains array of objects. want loop through , create target collection group "id" column shown on example. not use underscore js. have use javascript reduce method achieve this.

var targetcollection = [{      123456: [          { "id": "1", "name": "xxx", "age": "22" },          { "id": "1", "name": "yyy", "age": "15" },          { "id": "5", "name": "zzz", "age": "59" }      ],      789456: [          { "id": "1", "name": "xxx", "age": "22" },          { "id": "1", "name": "yyy", "age": "15" },          { "id": "5", "name": "zzz", "age": "59" }      ]  }]    var targetoutput = [{      123456: {          1: [{ "id": "1", "name": "xxx", "age": "22" }, { "id": "1", "name": "yyy", "age": "15" }],          5: [{ "id": "5", "name": "zzz", "age": "59" }]      },      789456: {          1: [{ "id": "1", "name": "xxx", "age": "22" }, { "id": "1", "name": "yyy", "age": "15" }],          5: [{ "id": "5", "name": "zzz", "age": "59" }]      }  }]

code snippet have tried didn't work    var newarray = [];  $.each(targetcollection, function (key, value) {      var newtarget = $(this);      var targetcollectionnew = newtarget.reduce(function (result, current) {          result[current.parentareaid] = result[current.parentareaid] || [];          result[current.parentareaid].push(current);          return result;      }, {});        newarray.push(targetcollectionnew);  });    console.log('newarray', newarray);

i have tried array reduce method , didn't work. please me.

the problem original attempt need have 2 loops because in first 1 newvalue object not array, there no reduce method on it.

the simpler solution use map (you use foreach or $.each) , reduce in second loop (i used simple for-in).

something this:

var targetcollection = [{      123456: [          { "id": "1", "name": "xxx", "age": "22" },          { "id": "1", "name": "yyy", "age": "15" },          { "id": "5", "name": "zzz", "age": "59" }      ],      789456: [          { "id": "1", "name": "xxx", "age": "22" },          { "id": "1", "name": "yyy", "age": "15" },          { "id": "5", "name": "zzz", "age": "59" }      ]  }];    var result = targetcollection.map(function(obj) {      (var key in obj) {          obj[key] = obj[key].reduce(function(prev, curr) {              if (!prev[curr.id]) prev[curr.id] = [];              prev[curr.id].push(curr);              return prev;          }, {});      }      return obj;  });    document.write('<pre>' + json.stringify(result, null, 4) + '</pre>');


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -