-1

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

}

Cryonic
  • 21
  • 4
  • 1
    the later should be an array, or give a syntax error. – Nina Scholz Jul 27 '16 at 07:53
  • Oh - I didn't notice, thanks – Cryonic Jul 27 '16 at 07:58
  • Note: You're not combining "two JSON objects." You're building a combination of objects (and what you want to do is build an array of objects). Once you've parsed your local storage strings, you're not dealing with JSON anymore. JSON is a *textual notation* for data exchange and storage. [(More)](http://stackoverflow.com/a/2904181/157247) – T.J. Crowder Jul 27 '16 at 07:59

2 Answers2

0

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));
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Change you endJson to a array

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);
    endJson.push(JSON.parse(localStorage.getItem(sel.options[i].text)));
}
// Write the new item to localStorage
localStorage.setItem(combName,JSON.stringify(endJson));

}
madalinivascu
  • 32,064
  • 4
  • 39
  • 55