javascript - Grouping objects in an array by multiple keys -
initially, i've array:
[{ "vendorid": 1, "vendorname": "vendor1", "maxfilelimit": 2, "uploadfilename": "voice1.xlsx" }, { "vendorid": 1, "vendorname": "vendor1", "maxfilelimit": 2, "uploadfilename": "ven1_voice.xlsx" }, { "vendorid": 2, "vendorname": "vendor2", "maxfilelimit": 2, "uploadfilename": "voice2.xlsx" }, { "vendorid": 2, "vendorname": "vendor2", "maxfilelimit": 2, "uploadfilename": "ven2_voice.xlsx" }]
i want file names in array no repetition of records. so, expect output similar following:
[{ "vendorid": 1, "vendorname": "vendor1", "maxfilelimit": 2, "uploadfilename": ["voice1.xlsx", "ven1_voice.xlsx"] }, { "vendorid": 2, "vendorname": "vendor2", "maxfilelimit": 2, "uploadfilename": ["voice2.xlsx", "ven2_voice.xlsx"] }]
i found solutions d3.js, alasql not getting output expected
you can use array#reduce
, inside can store result in object , extract values using object.values()
.
var data = [{"vendorid": 1,"vendorname": "vendor1","maxfilelimit": 2,"uploadfilename": "voice1.xlsx"},{"vendorid": 1,"vendorname": "vendor1","maxfilelimit": 2,"uploadfilename": "ven1_voice.xlsx"},{"vendorid": 2,"vendorname": "vendor2","maxfilelimit": 2,"uploadfilename": "voice2.xlsx"},{"vendorid": 2,"vendorname": "vendor2","maxfilelimit": 2,"uploadfilename": "ven2_voice.xlsx"}]; var result = data.reduce((hash, obj) => { let key = obj.vendorid+'|' +obj.vendorname+'|' +obj.maxfilelimit; if(hash[key]) hash[key].uploadfilename.push(obj.uploadfilename); else { hash[key] = obj; hash[key].uploadfilename = [obj.uploadfilename]; } return hash; },{}); console.log(object.values(result));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment