Concat并根据数组中的键删除一些json元素

时间:2019-02-14 05:59:55

标签: javascript arrays json object

我有一个JSON数组对象,该对象的属性为id,其中包含多个条目,每个条目都具有更多属性。我想基于此id合并这些对象并删除冗余数据。同样,相同的id值将彼此相邻。查看以下数据以了解更多信息:

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 obj = [  {"merchantId":13075121312, "p1":"R", "p2":"R", "p3":"R"}
            ,{"merchantId":9160507252, "p1":"R", "p2":"R", "p3":"R"}
        ] ;

任何帮助将不胜感激。我尝试了以下功能,该功能不起作用:

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;
}

谢谢

3 个答案:

答案 0 :(得分:4)

您可以尝试使用Array.reduceObject.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);

答案 1 :(得分:3)

您可以使用forEach()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);

答案 2 :(得分:1)

您可以简单地使用for循环遍历数组,然后将对象的唯一ID设置为属性,并在找到对象时更新该对象属性。

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);