How to remove elements from object of arrays
Solution 1:
const medici = ["Person1","Person2", "Person3", "Person4", "Person5", "Person6" ];
const gironi = ["Lun", "Mar", "Mer","Gio","Ven"];
const presenti = {};
for (const giorno of gironi) {
presenti[giorno] = [...medici];
}
presenti["Ven"].splice(presenti["Ven"].indexOf("Person1"), 1);
console.log(presenti);
Your problem has to do with memory reference, when you equate two variables you are not creating another identical object but copying the object reference from one variable to another, so if you modify X
you change Y
, to correct you can create another Array using the spread operator [...medici]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Solution 2:
When you build your object all the arrays have the same reference so you will need to slice
medici
on each object value. Take a look to Copy array by value
Now you can use method.
let medici= ["Person1","Person2", "Person3", "Person4", "Person5", "Person6" ];
let giorni = ["Lun", "Mar", "Mer","Gio","Ven"]; let presenti ={};
for (let giorno of giorni){ presenti[giorno] = medici.slice(); }
let giorno="Ven";
let nome="Person1";
presenti[giorno].splice(presenti[giorno].indexOf(nome), 1);
console.log(presenti)