JS:将两个JSON对象合并为一个,但不制作数字索引

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

本文关键字:一个 索引 数字 合并 两个 JSON JS 对象      更新时间:2023-09-26

我有一个本地存储,JSON保存为字符串。我想将所有选定的JSON(通过选择)合并为一个新的JSON。我当前的代码是:

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

使用该代码,我得到一个元素,它看起来如下:

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

但我需要这样的格式:

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

有人知道怎么解决这个问题吗?

编辑:感谢您的解决方案,T.J.Crowder

这是我的新代码:

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

}

创建一个数组,而不是一个普通对象,请参阅注释行:

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

将endJson更改为数组

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