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 which 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));
}
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));
}