Cryonic Cryonic - 4 months ago 18
Javascript Question

JS: Combine two JSON objects into one, but without making a numeric index

i've got a localstorage, where JSONs are saved as string. I want to combine all selected JSONs (via selection) into a new one.
My current code is this:

function combine() {
var combName = prompt("Please enter a group name", "Group1");
var sel = document.getElementById("listComb");
var endJson={};

for(var i=0;i<sel.options.length;i++) {
alert(sel.options[i].text);
$.extend(endJson, endJson, JSON.parse(localStorage.getItem(sel.options[i].text)));
}
// Write the new item to localStorage
localStorage.setItem(combName,JSON.stringify(endJson));

}


With that code, i get an element wich looks like the following:

{
"0": {
"a": ""...
},
"1": {
"a": ""...
}
}


But i need a format like this:

[
{
"a": ""...
},
{
"a": ""...
}
]


Does anybody know how to fix this?

EDIT:
Thanks for the solution, T.J. Crowder

here's my new code:

function combine() {
var combName = prompt("Please enter a group name", "Group1");
var sel = document.getElementById("listComb");
var combined = []; // <== Array

for(var i=0;i<sel.options.length;i++) {
combined[i] = JSON.parse(localStorage.getItem(sel.options[i].text)); // <== Add to it
}

// Write the new item to localStorage
localStorage.setItem(combName, JSON.stringify(combined));


}

Answer

Create an array, not a plain object, see commented lines:

function combine() {
    var combName = prompt("Please enter a group name", "Group1");
    var sel = document.getElementById("listComb");
    var combined = []; // <== Array

    for(var i=0;i<sel.options.length;i++) {
        combined[i] = JSON.parse(localStorage.getItem(sel.options[i].text)); // <== Add to it
    }

    // Write the new item to localStorage
    localStorage.setItem(combName, JSON.stringify(combined));
}