Get specific values form JSON Table with javascript over IDs

105 Views Asked by At

I have the following problem:

I have a JSON table with the data I need (found this on the internet since it is nearly what I need)

var testext ={"key1":[
        {
            "firstName":"Ray",
            "lastName":"Villalobos",
            "joined":2012
        },
        {
            "firstName":"John",
            "lastName":"Jones",
            "joined":2010
        }
]}

document.getElementById("demo").innerHTML=testext.key1[0].firstName;

This works fine but as you can see I still need an index [0] to get to the dataset I need.

I need to to this without this index...

like this here:

var testext = {
 "key1": ["string1/1", "string1/2" ],
 "key2": ["string2/1", "strin2/2"] 

};



document.getElementById("demo").innerHTML = testext['key1'][0];

just combined so my variable would be something like :

document.getElementById("demo").innerHTML = testext['key1'].['firstname'];

Anyone an idea on how I can do this?

Thanks in advance.

1

There are 1 best solutions below

1
On BEST ANSWER

You are almost correct. Restructure your array into an associative array of associative arrays. You can call them by array_name['first_index']['second_index'].

var testext = {
  "key1": {
    "firstName": "Ray",
    "lastName": "Villalobos",
    "joined": 2012
  },
  "key2": {
    "firstName": "John",
    "lastName": "Jones",
    "joined": 2010
  }
};

document.getElementById("demo").innerHTML = testext['key1']['firstName'];
<div id="demo">Default</div>