-1

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

  • What have you attempted? Is your data JSON or an object? If JSON, first parse it into an object. – user1599011 Mar 29 '22 at 14:06
  • Parse the JSON to an array, remove array any entries with the same `trait-type` property as any previous entry, and stringify the array back into JSON. Have you tried to write any code that you can show in the question? – traktor Mar 29 '22 at 14:08

3 Answers3

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

Saren
  • 888
  • 4
  • 10
  • 22
-2

try this

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

 console.log(noDuplicatesArr);
Serge
  • 28,094
  • 4
  • 11
  • 35
-2

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);
Nick
  • 411
  • 9
  • 27