Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat and remove some json elements based on key in an array

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

like image 555
Atul Kumar Avatar asked Dec 29 '25 04:12

Atul Kumar


1 Answers

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);
like image 94
Nikhil Aggarwal Avatar answered Dec 31 '25 18:12

Nikhil Aggarwal