0

Lets say I've a JSON object like this stored in a file maj.json, which I import into my main.js file like this

maj.json

{
  "prop1": {
    "p1": 12,
    "p2": "qwer"
  },
  "prop2": {
    "p1": 34,
    "p2": "asdf"
  },
  "prop3": {
    "p1": 56,
    "p2": "zxcv"
  }
}

In main.js

var js = require("./maj.json");

Now I've an array like this

var prop = ["prop2", "prop3"];

How can I get the properties listed in say, array prop from js. I tried like this, but it's not working. I'm getting undefined result with this approach.

for(str in prop) {
    console.log(js.prop[str]);
}

output for this :

undefined
undefined

How can I do something like this in the right way?

EDIT More importantly how can i do this for inner properties like access prop2.p2 etc. dynamically, i.e both prop2 and p2 are given dynamically?

user3248186
  • 1,518
  • 4
  • 21
  • 34

0 Answers0