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.
2 Answers 2
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);
}
1 Comment
[key] resulted in exactly what I wanted. Here's a fiddle that shows it: jsfiddle.net/84w6F/1 It is working as intended. Since there are 2 entries, you are appending the rows twice inside the loop:
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.
Comments
Explore related questions
See similar questions with these tags.
data in "entries" to be exactly the samedo you mean you want to output what is in the json into#agenda?