angularjs - How to add several same key object data in one key/value pair Javascript? -


this question has answer here:

i have data this:

[{     "key":"a",     "data":"1"   }, {     "key":"b",     "data":"2"   }, {     "key":"c",     "data":"12"  }, {     "key":"a",     "data":"6"   }, {     "key":"b",     "data":"4"   }] 

output want is:

[     {         "key":"a",         "value":[{"data":"1"},{"data":"6"}]     },     {         "key":"b",         "value":[{"data":"2"},{"data":"4"}]     },     {         "key":"c",         "value":[{"data":"12"}]     } ] 

i want output in javascript or typescript dynamically json data dynamic .

can please help.

you use hash table , group items key property.

if group not exist, create new group key , values array. ten puth new object result array. later push actual value values array.

var data = [{ key: "a", data: "1" }, { key: "b", data: "2" }, { key: "c", data: "12" }, { key: "a", data: "6" }, { key: "b", data: "4" }],      hash = object.create(null),      result = data. reduce(function (r, o) {          if (!hash[o.key]) {              hash[o.key] = { key: o.key, value: [] };              r.push(hash[o.key]);          }          hash[o.key].value.push({ data: o.data });          return r;      }, []);    console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -