Queremos eliminar el nodo duplicado de JSON. Este nodo se eliminará si los valores de trait_type son iguales
Aquí está JSON
[ { "trait_type": "Background", "value": "Yellow" }, { "trait_type": "A", "value": "None" }, { "trait_type": "B", "value": "Male Body Grey Color" }, { "trait_type": "A", "value": "Outfit" } ]A JSON final debería gustarle esto.
[ { "trait_type": "Background", "value": "Yellow" }, { "trait_type": "A", "value": "None" }, { "trait_type": "B", "value": "Male Body Grey Color" } ]Por favor ayuda
Gracias
Así que supongo que su json es una matriz de javascript, de lo contrario use JSON.parse para convertirlo.
Entonces, lo que quiere es eliminar el valor doble en la matriz y, para ser justos, hay mucho que hacer, yo personalmente uso un Conjunto para hacer eso, pero para ser "amigable para principiantes", usaré un gran objeto temporal para almacenar valor y recuperarlos por una referencia
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]); });Esta función pura debería hacer:
function filterUnique(data){ const unique = {}; data.forEach(el => { unique[el.trait_type] = el; }); return Object.values(unique); } // const filteredJSON = filterUnique(json);prueba esto
var noDuplicatesArr = origArr.filter((v,i,a)=>a.findIndex(v2=>(v2.trait_type===v.trait_type))===i); console.log(noDuplicatesArr);