Javascript: Data Object merging -
i wondering if there's way merge element in object if have same property.
here mean:
var dummy = { data: [ {name: 'a', info: '1'}, {name: 'b', info: 'a'}, {name: 'c', info: '2'}, {name: 'a', info: '2'}, {name: 'b', info: '2'} ] }; var expected_results = { data: [ {name: 'a', info: '1,2'}, {name: 'b', info: 'a,2'}, {name: 'c', info: '2'} ] } //todo if same name merge if not seperate var plugin = { unique: { list: [] }, merge: function(params) { var lists = plugin.unique.list; lists.push(params[0]); //first unique $.each(params, function(index, item) { if(index !== 0) { $.each(lists, function(index, list) { if(list.name === item.name) { list.info += ',' + item.info; } else { lists.push(item); } }) } }) return lists; } }; console.clear(); var list = plugin.merge(dummy.data); console.log('result',list);
i think i'm close not quite sure whent wrong loop...:(
to honest, if you're going grouping key might use object rather array returned data structure. easier manipulate.
function squish(dummy) { // pass in initial empty object // if key isn't there, create , use array // value - push in value var out = dummy.data.reduce(function (p, c) { if (!p[c.name]) p[c.name] = []; p[c.name].push(c.info); return p; }, {}); // flatten arrays each key object.keys(out).foreach(function (el) { out[el] = out[el].join(','); }); // return expected_result return out; } squish(dummy);
output
{ "a": "1,2", "b": "a,2", "c": "2" }
but, if want have array of objects, that's simple enough too:
function squish2(dummy) { var out = dummy.data.reduce(function (p, c) { if (!p[c.name]) p[c.name] = []; p[c.name].push(c.info); return p; }, {}); return object.keys(out).map(function (el) { return { name: el, info: out[el].join(',') }; }); }
output
[ { "name": "a", "info": "1,2" }, { "name": "b", "info": "a,2" }, { "name": "c", "info": "2" } ]
Comments
Post a Comment