0

I am searching to delete duplicate object stored in my array. This object are sent in JSON. This is its structure :

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

In this case, the first or second object called name1 should be delete because they are exactlly the same.

This is algorithm I use to delete the duplicate but it delete all the object in my array...

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;

Thank for your help.

2 Answers 2

1

in your nested loop, you should skip the current object:

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
Sign up to request clarification or add additional context in comments.

3 Comments

Ok thanks it works but I have null values now for the objet deleted. Is it possible to remove the null values in the loop ?
this is another topic. please try to find an answer, and if there isn't, ask another question
1

Firstly it's normal if your algorithm delete all the object because, your loop test firstly the current object

see this link to resolve your problem:Remove duplicates from an array of objects in javascript

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.