Reputation: 700
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
Upvotes: 2
Views: 665
Reputation: 3386
you can simply use for loop to iterate over array then set unique id on object as an property and update that object property when same is found.
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",}
] ;
var newObj = {};
for(var i = 0;i < obj.length; i++) {
var item = obj[i];
if(!newObj.hasOwnProperty(item['Id'])) { newObj[item['Id']] = {};}
newObj[item['Id']] = {'merchantId':item['Id'], ...newObj[item['Id']], ...item};
}
var val = Object.values(newObj);
console.log(val);
Upvotes: 1
Reputation: 36574
You can do that using forEach()
and Spread in object literals
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",}
]
let result = [];
obj.forEach(a => {
let same = result.findIndex(b => b.Id === a.Id);
if(same > -1) result[same] = {...result[same],...a};
else result.push(a);
})
console.log(result);
Upvotes: 3
Reputation: 28465
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);
Upvotes: 5