1

I am trying to traverse a JSON file using a variable that gets set earlier in my script.

Example of the JSON:

{
    "page1": [{
        "template": "temp1",
        "other": "example"
    }],
    "page2": [{
        "template": "temp2",
        "other": "example"
    }],
    "page3": [{
        "template": "temp3",
        "other": "example"
    }]
}

The variable can be one of three items... page1, page2, page3

As I said I am setting the variable further up in the code so say the variable is:

var getid = "page1";

What I want to do is, if the variable is "page1", then get the "template" value of "temp1".

my console.log

console.log(json[getid]);

returns

[{template: "temp1"}]

but I don't really know how to go any further. Everything I try returns "undefined" or an error.

As I said, I want to get "temp1" in this example.

Can anyone help me along?

If you need more info, please let me know.

Thanks,

masahs
  • 25
  • 6

2 Answers2

0

var json = {
    "page1": [{
        "template": "temp1",
        "other": "example"
    }],
    "page2": [{
        "template": "temp2",
        "other": "example"
    }],
    "page3": [{
        "template": "temp3",
        "other": "example"
    }]
};

var getid = "page1";

console.log(json[getid][0].template);

you are very close to the solution, just access object inside array you are done.

json[getid][0].template

will do

satwik
  • 587
  • 5
  • 13
0

You can use the code below. json[getid] return an array of one object So you need to access the first item of array using [0] which will return object object and then use .template

let json = {
    "page1": [{
        "template": "temp1",
        "other": "example"
    }],
    "page2": [{
        "template": "temp2",
        "other": "example"
    }],
    "page3": [{
        "template": "temp3",
        "other": "example"
    }]
}
var getid = "page1";
console.log(json[getid][0].template);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73