简体   繁体   中英

JavaScript - Item doesn't get added to array

I've done a jsFiddle . Some code below.

My expected output is

[{
    "support_advice": [{
            "id": "A",
            "type": "checkbox",
            "text": "",
            "value": "A"
        },
        {
            "id": "C",
            "type": "checkbox",
            "text": "",
            "value": "C"
        }
    ]
}]

However I get

[{
    "support_advice": [{
        "id": "C",
        "type": "checkbox",
        "text": "",
        "value": "C"
    }]
}]

I thought result[elem[i].name] = matches; would add another item rather than replace what's there already

HTML

<form id="rn_QuestionSubmit">
<input name="support_advice" id="A" type="checkbox" value="A" checked>
<input name="support_advice" id="B" type="checkbox" value="B">
<input name="support_advice" id="C" type="checkbox" value="C" checked>
</form>

JavaScript

var elem = document.getElementById('rn_QuestionSubmit').elements;

            var a = [];
            var result = {};

            for(var i = 0; i < elem.length; i++)
            {
                var matches = [];
                var item = {};
                item.id = elem[i].id;
                item.type = elem[i].type;
                if (elem[i].type === 'select-one') {
                    item.text = document.getElementById(elem[i].id).options[document.getElementById(elem[i].id).selectedIndex].text;
                }
                else {
                    item.text = '';
                }

                if (elem[i].type === 'radio' || elem[i].type === 'checkbox') {
                    if (document.getElementById(elem[i].id).checked) {

                        item.value = document.getElementById(elem[i].id).value;
                        matches.push(item);
                        result[elem[i].name] = matches;
                    }
                }
                else {
                    item.value = elem[i].value;
                    matches.push(item);
                    result[elem[i].name] = matches;
                }
            } 

            a.push(JSON.stringify(result));
            console.log('['+a.join(',') + ']');
            return('['+a.join(',') + ']');

a lot of unneeded code could be cleaned up here...

var elem = document.getElementById('rn_QuestionSubmit').elements;

        var a = [];
        var result = {};

        for(var i = 0; i < elem.length; i++)
        {
            var element = elem[i];
            var item = {};
            item.id = element.id;
            item.type = element.type;
            if (element.type === 'select-one') {
                item.text = element.options[element.selectedIndex].text;
            }
            else {
                item.text = '';
            }

            if (element.type === 'radio' || element.type === 'checkbox') {
                if (element.checked) {
                    item.value = element.value;
                    if (result[element.name]) { result[element.name].push(item) } else { result[element.name] = [item]};
                }
            }
            else {
                item.value = elem[i].value;
                if (result[element.name]) { result[element.name].push(item) } else { result[element.name] = [item]};
            }
        } 

        a.push(JSON.stringify(result));
        console.log('['+a.join(',') + ']');
        return('['+a.join(',') + ']');

you need to actually decide to push or create a new array on each element.

fiddle: https://jsfiddle.net/0jhyj4wv/

This is appening because you are assigning the matches array each time to the support_advicce property.

To make sure of what's happening you put this console.log in to your code:

console.log("before", result[elem[i].name]);
result[elem[i].name] = matches;
console.log("after", result[elem[i].name]);

And you will get:

  1. before undefined
  2. after [0: {id: "A", type: "checkbox", text: "", value: "A"}]
  3. before [0: {id: "A", type: "checkbox", text: "", value: "A"}]
  4. after [0: {id: "C", type: "checkbox", text: "", value: "C"}]

Solution

Instead of

result[elem[i].name] = matches;

you could use (using ES6)

if(typeof result[elem[i].name] === "undefined") result[elem[i].name] = [];          
result[elem[i].name].push(...matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM