2

Let's say I have some JSON:

{
    "An unknown value": {
        "some": "values",
        "I": "want",
        "to": "access"
    }
}

As you can see, I want to access the data within an object with an unknown name. This code will run in a Node.js environment. Any help is appreciated.

3
  • 1
    Does for .. in not meet your need? Commented Oct 28, 2015 at 0:38
  • 1
    Object.keys(object) returns an array of the object's own, enumerable property names. Iterate over that. Commented Oct 28, 2015 at 0:41
  • @RobG Thanks! I was not aware of this method! Commented Oct 28, 2015 at 0:50

3 Answers 3

4

https://jsfiddle.net/ygac8dgg/

var object = {
    "An unknown value": {
        "some": "values",
        "I": "want",
        "to": "access"
    },
    "Another":"is",
    "still":"uknown"
};

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
        console.log("property:",property);
        console.log("value:",object[property]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

For everyone's reference, here's RobG's suggestion as a fiddle:
https://jsfiddle.net/m4jgyvp0

const object = {
   'An unknown value': {
      'some': 'values',
      'I':    'want',
      'to':   'access'
      },
   'Another': 'is',
   'still':   'unknown'
   };

const keys = Object.keys(object);
const array = keys.map(key => ({ key: key, value: object[key] }));

keys

keys can be converted to an array of key-value pairs with the .map() function, or you could iterate over keys with .forEach().

Comments

0

Reading my question again, it is very vague/unclear, and I can't seem to remember the context of this.

However in other situations, where I need to access an object via a dynamic key, one can use:

const key: string = "aKeyFromSomeWhere"
const value = object[key]

rather than object.aKnownKey

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.