0

Given the following object, how would I dynamically access both levels of data?

var object = {
    "one": {
        "0": "foo",
        "1": "foo foo",
        "2": "foo foo foo",
        "3": "foo foo foo foo",
        "4": "foo foo foo foo foo"
    },
    "two": {
        "0": "bar",
        "1": "bar bar",
        "2": "bar bar bar",
        "3": "bar bar bar bar",
        "4": "bar bar bar bar bar"
    }
};

Shouldn't I be able to do something along the lines of:

var outer = "one",
    inner = "3";

console.log(object[outer][inner]);

And have the output be "foo foo foo foo"?

6
  • What happened when you tried? Commented Jun 21, 2017 at 4:41
  • Yes that would be the exact output of the code as you have typed it. Commented Jun 21, 2017 at 4:42
  • If u r having trouble traversing huge collections / objects, try using underscore/lodash and these util libraries have out of the box methods like pluck(), map() etc. which can be useful . Commented Jun 21, 2017 at 4:44
  • Yea this works just fine. What seems to tbe the problem Commented Jun 21, 2017 at 4:48
  • For whatever reason, jQuery and my hot reloading were breaking in some spectacular way. I now understand that I am a fool. Thank you all for your comments and helping me to realize it! Commented Jun 21, 2017 at 20:53

3 Answers 3

3

Yes. And it does.

$ cat so2.js
var object = {
  "one": {
    "0": "foo",
    "1": "foo foo",
    "2": "foo foo foo",
    "3": "foo foo foo foo",
    "4": "foo foo foo foo foo"
  },
  "two": {
    "0": "bar",
    "1": "bar bar",
    "2": "bar bar bar",
    "3": "bar bar bar bar",
    "4": "bar bar bar bar bar"
  }
};

var outer = "one", inner = "3";

console.log(object[outer][inner]);

$ node so2.js foo foo foo foo

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

1 Comment

Hot reloading and jQuery weren't playing nice for some reason. It does work, and I am just embarrassed now.
0

You could try out using the index, but first you need to get the index of the keys "one","two". Something like :

object[Object.keys(object)[0]][1]     // "foo foo"
object[Object.keys(object)[1]][1]     // "bar bar"

2 Comments

Object.keys returns the array of keys for the object and Object.keys(object)[0] will return one of the keys, not an index.
Yes exactly !! I
0

Here is the code for accessing all the values as per your json object :

for(var first in object)
{
    for(var second in object[first])
    {
        console.log(object[first][second]);
    }
}

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.