-1

I have the following object (called message_tags):

{
  "88": [
    {
      "id":"864794113531613",
      "name":"Luis Angel Rodriguez",
      "type":"user",
      "offset":88,
      "length":20
    }
  ],
  "112": [
    {
      "id":"640891773501",
      "name":"Carl Champion Jr.",
      "type":"user",
      "offset":112,
      "length":17
    }
  ]
} 

I can get values from it using something like this:

var id = message_tags[88][0].id

but where it says 88 and 112 will always be different numbers, and the only way I can tell what number it will be is by getting the offset, which of course if further inside the object.

How can I iterate through this object not knowing what those numbers can be? (can't use message_tags[0] as it returns undefined

Justin White
  • 714
  • 7
  • 22

2 Answers2

1

You can iterate over the object like this:

for (var thisKey in message_tags) { 
  if (message_tags.hasOwnProperty(thisKey)) {
    console.log(thisKey);
    console.log(message_tags[thisKey]);
  }
}

If you are 100% certain that the prototype chain is clean, you can leave out the hasOwnProperty() check. If you don't know what the means, definitely leave it in.

Trott
  • 66,479
  • 23
  • 173
  • 212
1

Try this:

obj = {
  "88": [
    {
      "id":"864794113531613",
      "name":"Luis Angel Rodriguez",
      "type":"user",
      "offset":88,
      "length":20
    }
  ],
  "112": [
    {
      "id":"640891773501",
      "name":"Carl Champion Jr.",
      "type":"user",
      "offset":112,
      "length":17
    }
  ]
}

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    alert(key + " -> " + obj[key]);
  }
}
ankur
  • 157
  • 7