0

Imagine we have this JSON:

{ "A" : {"A1": "1" } }

How can I extract the actual index A1 ? So that I can use it in JS like:

var index = "A1";
0

1 Answer 1

4

edit — in case you mean, "How can I extract the value at index A1", then you'd just use the dot or bracket operators:

var value = object.A.A1;

or

var index = "A1";
var value = object.A[index];

Else see below.


You can iterate through the property names of an object with the for ... in loop:

for (var propertyName in object) {
  // ...
}

The loop will also include properties from the prototype chain, so you can avoid that (if you want) with a function called hasOwnProperty:

for (var name in object) {
  if (object.hasOwnProperty(name)) {
    // really is a local property
  }
}

Newer browsers support a way to get the property names as an array:

var names = Object.keys( yourObject );

That list will only include "own" properties; that is, those for which hasOwnProperty() would return true.

Finally, there are ways that properties can be defined such that they're not "enumerable". Usually when that's done, you would generally not want to see them in for ... in anyway.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.