I have a JSON array object which has a property id with several entry and each entry has some more property. I want to merge these object on the basis of this id and delete the redundant data. Also same id value will be adjacent to each other. Look below data to understand more :
var obj = [ {"Id":13075121312, "p1":"R"}
,{"Id":13075121312, "p2":"R"}
,{"Id":13075121312, "p3":"R"}
,{"Id":9160507252, "p1":"R",}
,{"Id":9160507252, "p2":"R",}
,{"Id":9160507252, "p3":"R",}
] ;
I need to convert this array of object as following :
var obj = [ {"merchantId":13075121312, "p1":"R", "p2":"R", "p3":"R"}
,{"merchantId":9160507252, "p1":"R", "p2":"R", "p3":"R"}
] ;
Any help would be appreciated. I tried the following function it is not working :
function jsonConcat(obj) {
for(var i=0; i<obj.length-1; ){
if(obj[i]['d'] === obj[i+1]['Id']){
obj[i]['Id'] = obj[i+1]['Id'];
delete json[obj[i+1]];
}
i = i + 1;
}
return obj;
}
Thanks
You can try following using Array.reduce and Object.values
var obj = [ {"Id":13075121312, "p1":"R"},{"Id":13075121312, "p2":"R"},{"Id":13075121312, "p3":"R"},{"Id":9160507252, "p1":"R"},{"Id":9160507252, "p2":"R"},{"Id":9160507252, "p3":"R"}];
obj = Object.values(obj.reduce((a,{Id, ...rest}) => {
a[Id] = a[Id] || {merchantId:Id};
Object.assign(a[Id], rest);
return a;
}, {}));
console.log(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With