从对象数组中删除重复项

时间:2016-05-05 11:41:42

标签: javascript jquery arrays json

我有一个名为

的json对象的对象

mainobject =

 Array[2]
>0: object
 >Innerobject1 : Array[2]
  >0 : object
     Name : "Xavier"
     Dup  : "B"
  >1 : object
     Name : "Gh"
     Dup : "B"
>1: object
 >Innerobject2 : Array[2]
  >0 : object
     Name : "Cat"
     Dup :  "C"
  >1 : object
     Name : "Dog"
     Dup : "D"

我需要将“dup”设为“”,它已存在于第一个对象中(如果有的话)。我期望的输出是:

Array[2]
>0: object
 >Innerobject1 : Array[2]
  >0 : object
     Name : "Xavier"
     Dup  : "B"
  >1 : object
     Name : "Gh"
     Dup : ""
>1: object
 >Innerobject2 : Array[2]
  >0 : object
     Name : "Cat"
     Dup :  "C"
  >1 : object
     Name : "Dog"
     Dup : "D"

编辑:

json格式的对象: :

"[{"Innerobject1":[{"Name" :"Xavier","Dup":"B"},{"Name" :"Gh","Dup":"B"}]},
{"Innerobject2":[{"Name" : "Cat","Dup":"C"},{"Name":"Dog", "Dup":"D"}]}]"

2 个答案:

答案 0 :(得分:1)

我不太确定我已经解释了您发布的对象数组是否正确。但你可以这样做:

迭代数组并将您想要在对象中唯一的键存储起来。遇到更多时,请将新值设置为空字符串:

var seen = {};
mainobject.forEach(function(obj) {
   if (seen[obj.Name]) {
       obj.Name = "";
   }
   seen[obj.Name] = true;
});

您可能需要多次迭代,依赖于您获得的嵌套数组的数量:

var seen = {};
mainobject.forEach(function(inner_arr) {
   inner_arr.forEach(function(obj) {
       if (seen[obj.Name]) {
           obj.Name = "";
       }
       seen[obj.Name] = true;
    });
});

答案 1 :(得分:1)

使用Array.forEachObject.keys函数的解决方案:

var mainobject = JSON.parse('[{"Innerobject1":[{"Name" :"Xavier","Dup":"B"},{"Name" :"Gh","Dup":"B"}]},{"Innerobject2":[{"Name" : "Cat","Dup":"C"},{"Name":"Dog", "Dup":"D"}]}]');

mainobject.forEach(function(obj){
    Object.keys(obj).forEach(function(k){
        obj[k].forEach(function(o){
            if (this["Dup"]) {
                (this["Dup"].indexOf(o["Dup"]) !== -1)? o["Dup"] = "" : this["Dup"].push(o["Dup"]);
            } else {
                this["Dup"] = [o["Dup"]];
            }
        })
    });
}, {});

console.log(JSON.stringify(mainobject, 0, 4));

console.log输出:

[
    {
        "Innerobject1": [
            {
                "Name": "Xavier",
                "Dup": "B"
            },
            {
                "Name": "Gh",
                "Dup": ""
            }
        ]
    },
    {
        "Innerobject2": [
            {
                "Name": "Cat",
                "Dup": "C"
            },
            {
                "Name": "Dog",
                "Dup": "D"
            }
        ]
    }
]