Search code examples
javascriptjqueryarraysmultidimensional-arraydynamic-arrays

Building data into a multidimensional array in JavaScript


I'm trying to rebuild data structure from an existing JSON file. 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. 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.


Solution

  • You have a 1 dimensional array containing 2 entries here, not a multidimensional array.

    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.

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