Reputation:
I currently have a JSON object that my program creates dynamically. The object is valid and can be parsed with JSON.parse().
This is the object i am working with:
{
"1":
{
"name":"temporary",
"value":"5"
},
"2":
{
"name":"temporary 2",
"value":"10"
}
}
The code i am trying to use is:
var obj = JSON.parse(StringObj);
var count = Object.keys(obj).length;
for(var i = 0; i < count; i++){
console.log(obj[i].name + ": " + obj[i].value);
}
However, this is throwing an error in the console:
obj[i] is undefined
What am i doing wrong here? ive done this a thousand times before in different applications but cant figure out why it isn't working this time.
Upvotes: 2
Views: 36
Reputation: 337713
Your for
loop starts at 0
, yet the keys are 1
and 2
. You need to loop from 1
instead:
var obj = {
"1": { "name": "temporary", "value": "5" },
"2": { "name": "temporary 2", "value": "10" }
}
var count = Object.keys(obj).length;
for (var i = 1; i <= count; i++) {
console.log(obj[i].name + ": " + obj[i].value);
}
Alternatively you can avoid the issue by using a forEach()
loop over the keys:
var obj = {
"1": { "name": "temporary", "value": "5" },
"2": { "name": "temporary 2", "value": "10" }
}
Object.keys(obj).forEach(function(key) {
console.log(obj[key].name + ": " + obj[key].value);
});
Upvotes: 3