简体   繁体   English

使用JavaScript将数据构建到多维数组

[英]Building data into a multidimensional array in JavaScript

I'm trying to rebuild data structure from an existing JSON file. 我正在尝试从现有的JSON文件重建数据结构。 For the sake of example, I trimmed all the unnecessary code: 为了举例,我修剪了所有不必要的代码:

var entries = [
  {
    "band": "Weezer",
    "song": "El Scorcho"
  },
  {
    "band": "Chevelle",
    "song": "Family System"
  }
]

var rows = {};

for (var i = 0; i < entries.length; ++i) {

    var entry = entries[i];

    var t = "a";
    for (var key in entry) {
            rows[t] = t;
            t = t+"1";
    }    
    $("#agenda").append(JSON.stringify(rows));

}
$("#agenda").append("<br /><br /> In the end, it only shows the last one:<br />");
$("#agenda").append(JSON.stringify(rows));

There's also a fiddle that shows it better: http://jsfiddle.net/84w6F The aim of this example is to try and rebuild the data in "entries" to be exactly the same, by calling both the key and the value as variables. 还有一个小提琴可以更好地显示它: http : //jsfiddle.net/84w6F本示例的目的是通过将键和值都称为变量来尝试重建“条目”中的数据完全相同。 。 For some reason, I end up with a mess , and in the end when I try to read the array after the loop, it shows me only the last sub array. 由于某种原因,我最终陷入困境,最后,当我尝试在循环后读取数组时,它仅向我显示了最后一个子数组。

You have a 1 dimensional array containing 2 entries here, not a multidimensional array. 您有一个包含2个条目的1维数组,而不是多维数组。

Your outer loop, is iterating over the two objects in the array fine, and the inner loop is going over all the key value pairs in each object but it is only setting rows["a"] and rows["a1"] because each object in the array only has 2 properties. 您的外部循环很好地遍历了数组中的两个对象,而内部循环遍历了每个对象中的所有键值对,但是它仅设置rows["a"]rows["a1"]因为每个数组中的object仅具有2个属性。

I'm not entirely sure what you want to do with the data within the array, if you want to copy them completely then you can do something like this: 我不确定要对数组中的数据做什么,如果要完全复制它们,则可以执行以下操作:

var rows = [];

for (var i = 0; i < entries.length; ++i) {

    var entry = entries[i];

    var newObj = {};
    for (var key in entry) {
      newObj[key] = entry;
    }
    rows.push(newObj);
}

It is working as intended. 它按预期工作。 Since there are 2 entries, you are appending the rows twice inside the loop: 由于有2个条目,因此您要在循环内两次附加行:

for (var i = 0; i < entries.length; ++i) {

    var entry = entries[i];

    var t = "a";
    for (var key in entry) {
            rows[t] = t;
            t = t+"1";
    }    
    $("#agenda").append(JSON.stringify(rows));

}

What you are actually doing is that you are replacing rows['a'] and rows['a1'] repeatedly (instead of growing it) and appended it twice so that you saw the first result. 实际上,您实际上是在重复替换rows['a']rows['a1'] (而不是增大rows['a1'] )并将其附加两次,以便您看到第一个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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