2

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.

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

This worked. Cheers for that. however, My keys will not always be in order, for example if there are three items and the second is deleted, the keys will be 1 and 3. how can I get round this?
@DarrylWhalley in that case use the second method I showed as it loops over the keys no matter what order or value they have.
@RoryMcCrossan This was exactly what i was looking for. Thanks for that!