Home > other >  How can remove the node from JSON if values are same in JSON
How can remove the node from JSON if values are same in JSON

Time:03-29

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

CodePudding user response:

try this

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

 console.log(noDuplicatesArr);

CodePudding user response:

You can try something like this

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

  {
    "trait_type": "A",
    "value": "Outfit"
  }

];

const uniqueIDs = new Set();
let uniqueData = data.filter(x => {
  const duplicate = uniqueIDs.has(x.trait_type);
  uniqueIDs.add(x.trait_type);
  return !duplicate;
});

console.log(uniqueData);

CodePudding user response:

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

CodePudding user response:

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);
  • Related