I have a question about how I can delete the existing elements, for example, in my case “Tallas” is repeated, could you please help me? Thank you very much to those who are willing to help me to solve this problem
const data = [ { atributos: { Tallas: [{ id: 0, name: 'XS' }, { id: 1, name: 'S' }] }} , { atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }} , { atributos: { Tallas: [{ id: 0, name: 'XS' }] }} ]
The idea is to have this json format with the last “Tallas” since it is the last one that I added through my dynamic form.
const expected = [{ atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }} , { atributos: { Tallas: [{ id: 0, name: 'XS' }] }} ]
How do I do this is there a way to do it, I’ve tried with filter plus the findindex but I can’t get to eliminate the repetition of the json res= new.filter((arr, index, self) => index === self.findIndex( (t) => (t.attributes === arr.attributes )))
Advertisement
Answer
To unique the array of objects, we can use the Javascript Set
module, if the array has complex nested objects, we can stringify
each object before creating new Set
data. this below function will unique the array of complex objects.
function unique_array(array = []) { const newSetData = new Set(array.map((e) => JSON.stringify(e))); return Array.from(newSetData).map((e) => JSON.parse(e)); }