Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create object with key => value in javascript

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading