删除数组中的同一对象

时间:2016-05-06 13:05:36

标签: javascript arrays object duplicates

我正在搜索删除存储在我的数组中的重复对象。该对象以JSON格式发送。这是它的结构:

{  
  "name":"root",
  "children":[  
    {  
      "name":"name1",
      "children":[  
        {  
          "name":"name1",
          "level":1
        }
      ]
    },
    {  
      "name":"name1",
      "children":[  
        {  
          "name":"name1",
          "level":1
        }
      ]
    },
    {  
      "name":"name2",
      "children":[  
        {  
          "name":"name2",
          "level":3
        }
      ]
    }
  ]
}

在这种情况下,名为name1的第一个或第二个对象应该被删除,因为它们完全相同。

这是我用来删除副本的算法,但它删除了我的数组中的所有对象......

for (var z in player.children){
    var nameObject = playerchildren[z].name;
    //console.log(nameObject);
    for (var q in player.children){
        //console.log(player.children[q].name);
        if (nameObject == player.children[q].name){
            console.log(nameObject + " = " + myBubble.children[q].name);
           // delete player.children[z]; // Delete all ...
        } else {
            console.log(nameObject + " != " + player.children[q].name);
        }
    }
}
return player;

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在嵌套循环中,您应该跳过当前对象:

for (var z in player.children){
        var nameObject = playerchildren[z].name;
        //console.log(nameObject);
        for (var q in player.children){
            //console.log(player.children[q].name);
            if (nameObject == player.children[q].name){ 
                 // this is true if z == q. that's why all objects get deleted


for (var z in player.children){
            var nameObject = playerchildren[z].name;
            //console.log(nameObject);
            for (var q in player.children){
                //console.log(player.children[q].name);
                if ( q !== z && nameObject == player.children[q].name){ 
                     // now this should be better

答案 1 :(得分:1)

首先,如果您的算法删除了所有对象,这是正常的,因为您的循环测试首先是当前对象

请参阅此链接以解决您的问题:Remove duplicates from an array of objects in javascript