0

I have a code like this

var data = {
  "post": {
    "time": {
      "year": "2017",
      "month": "1"
    }
  }
}

and I want to use multi varible to get the data.post.time array I have written this code but doesn't work

var type = "post";
var name = "time";
console.log(data.type.name);

But it doesn't output the array of data.post.time How to fix it?

Andrew
  • 83
  • 1
  • 1
  • 10
  • `console.log(data[type][name]);` [**property accessors**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors). – ibrahim mahrir Jun 12 '17 at 12:37
  • I fixed it with the last part of the array needs to be quote since it's not a variable but I think someone have tell me that it's better to use dot than `[]` why – Andrew Jun 12 '17 at 12:42
  • They're the same, the only thing that matters is taste (the `.` is shorter and clearer than `[]`, that's all). In this case, however, you're obliged to use `[]` as it's the only way here. – ibrahim mahrir Jun 12 '17 at 12:44
  • Its not always the same, dot operator may be cleaner but JS prefers `[]`. For example, `var a= {0: "test"}; console.log(a.0);`. This statement will give an error while `console.log(a[0]);` would print "test" – Flying Gambit Jun 12 '17 at 12:50

0 Answers0