I am making an application and I have to dynamically add/remove values to an object in JavaScript, the point is, that I have to add the most updated values to the object and not just any.
var arreglo = [
{"id":0,"producto":["Tomate"],"productos_datos":["1-1-1","1","1","1","1"]}, // <- Este registro debe quedar eliminado, porque es antiguo
{"id":1,"producto":["Tomate"],"productos_datos":["1-1-1","1","1","1","1"]}, // <- Este registro debe quedar eliminado, porque es antiguo
{"id":2,"producto":["Tomate"],"productos_datos":["1-1-3","1","1","1","3"]}, // <- Este registro debe permanecer, porque es el mas actualizado
{"id":3,"producto":["Cebollin"],"productos_datos":["1-1-1","1","1","1","1"]}
]
I have tried with several codes but it does not update me, I have tried with a forEach and it only gives me the first value and not the most updated
var hash = {};
filteredCategories = arreglo.filter(function(current)
{
let go = current.id !== undefined ? String(current.id) + String(current.producto) + String(current.productos_datos) : String(current.id);
let exists = !hash[go] || false;
hash[go] = true;
return exists;
});
filteredCategories.forEach(category => {
if (!filteredCategories.find(cat => cat.id == category.id && cat.productos_datos == category.productos_datos)) {
const { id, producto, productos_datos } = category;
filteredCategories.push({ id, producto, productos_datos });
}
});
Starting from the arrangement that I leave here, I will put the result that I am looking for:
var arreglo = [
{"id":2,"producto":["Tomate"],"productos_datos":["1-1-3","1","1","1","3"]},
{"id":3,"producto":["Cebollin"],"productos_datos":["1-1-1","1","1","1","1"]}
]
As you can see, there are only two products and there are no repetitions, the products are up to date and it's fair, that's what I'm looking for, but I can't solve it
It seems that the only key that should not be repeated is product, with that we can use an object to store elements in it and use that key to delete any previous elements, once we use the object, we loop through the created object and reassemble the data as you expect , so a proposal for what you need would be the following: