I have an array of objects (opciones) and another array (visibles) where im trying to add the objects that are supposed to show up.
function next(ev, next) {
ev.preventDefault();
setToggle(next.siguiente);
let element = document.getElementById(next.siguiente);
opciones.map(
(opcion) => opcion.id === next.siguiente && visibles.push(opcion)
);
}
Next is the current object i’m passing onClick/submit.
SetToggle: i set visibility of the component i want to show.
next.siguiente – the next component ID that has to show up after this function is finished.
opciones – my initial array of objects
**visibles **- the array where i add the selected objects
and in my opciones.map function i’m trying to detect if the next component ID exists in the opciones array i want to push it into visibles array.
It works but im obviously getting duplicates the way i’m doing it right now.
So pretty much siguiente would be the ID of the next object / component i want to display.
How would i be able to check if visibles already has the added object before i add it again?
i tried something like:
function next(ev, next) {
ev.preventDefault();
setToggle(next.siguiente);
let element = document.getElementById(next.siguiente);
if (visibles.includes(next)) {
console.log("already exists");
} else {
opciones.map(
(opcion) => opcion.id === next.siguiente && visibles.push(opcion)
);
}
}
but it doesn’t really work. I’m getting duplicated keys when displaying the list and it keeps adding to the array.
Any help or recommendation in general to improve this would be appreciated! Thank you in advance.
2
Answers
Used vikashraj144's answer for reference. His function added the entire Array of objects into the new array of objects without duplicating the objects. I needed to select and object and check if it already exists in the array before adding it.