Im’ trying to create an object in a loop which contain key => [value], if key exist, add the value.
I tried like this :
let dataName = [];
let obj = {};
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
obj[name] = [checkbox.id]
dataName.push(obj);
}
});
And when I click the value is override instead being added. How to add value by keys when the checkbox is checked ?
>Solution :
You need to create a new object for each iteration
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
let obj = {};
obj[name] = [checkbox.id]
dataName.push(obj);
}
});
Also, if obj[name] is not working, try obj[checkbox.getAttribute("name")] = ...;
Also, you can select only checked checkboxes using
document.querySelectorAll("input:checked");