'How can remove the node from JSON if values are same in JSON [duplicate]

We want to remove duplicate node from JSON. This node will be removed if trait_type values are same

Here is JSON

[
    {
      "trait_type": "Background",
      "value": "Yellow"
    },
    {
      "trait_type": "A",
      "value": "None"
    },
    {
      "trait_type": "B",
      "value": "Male Body Grey Color"
    },
    
    {
      "trait_type": "A",
      "value": "Outfit"
    }

  ]

Final JSON should like this.

 [
    {
      "trait_type": "Background",
      "value": "Yellow"
    },
    {
      "trait_type": "A",
      "value": "None"
    },
    {
      "trait_type": "B",
      "value": "Male Body Grey Color"
    }

  ]

Please help

Thanks



Solution 1:[1]

So I guess your json is a javascript array, else use JSON.parse to convert it.

So what you want is to delete double value in the array and to be faire there is a lot to do it, I personnaly use a Set to do that but to be "beginner friendly" I will use a big temporary object to store value and retrive them by a reference

const data = [
    {
      "trait_type": "Background",
      "value": "Yellow"
    },
    {
      "trait_type": "A",
      "value": "None"
    }]

const tmpObject = {};

data.forEach((d) => {
   if (!tmpObject[d?.trait_type]) { 
     tmpObject[d.trait_type] = d; // we only push data indide the object if the keys does not exist and the keys is the value you want to be unique so once you have a value matching we will not add the next data (with same trait_type) inside the object
   }
});

// now build the new array is like

theArrayYouWant = [];
Object.keys(tmpObject).forEach((d) => {
  theArrayYouWant.push(tmpObject[d]);
});

Solution 2:[2]

try this

 var noDuplicatesArr =  origArr.filter((v,i,a)=>a.findIndex(v2=>(v2.trait_type===v.trait_type))===i);

 console.log(noDuplicatesArr);

Solution 3:[3]

This pure function should do:

function filterUnique(data){
  const unique = {};
  
  data.forEach(el => {
    unique[el.trait_type] = el;
  });
  
  return Object.values(unique);
}

//
const filteredJSON = filterUnique(json);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saren
Solution 2 Serge
Solution 3 Nick