0

If I were to have a Json file that looked something like this:

{
  "numbers":{
     "firstnum":"one",
     "secondnum":"two",
     "thirdnum":"three",
     "fourthnum":"four",
     "fifthnum":"five"
  }
}

and I wanted to get the value of the third number (three) using JavaScript. Instead of doing...

jsonObject.numbers.thirdnum

Is there a way I can select that value using some sort of children or index method? for example something kind of like this...

jsonObject.numbers.children[2]
AbrahamKMS
  • 85
  • 5
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+get+nth+key+of+object) of [How to select nth item inside the object](https://stackoverflow.com/q/35722324/4642212). – Sebastian Simon Dec 09 '20 at 21:58

3 Answers3

3

First you have to convert your JSON to JavaScript:

const object = JSON.parse(string_of_json);

Then you can get an array of an objects properties, keys, or both with the appropriate methods on the Object class.

Object.keys(object.numbers)[2];
Object.values(object.numbers)[2];
Object.entries(object.numbers)[2];

Since order isn't guaranteed, this isn't generally useful unless you want to do something to every item item you get back.

If you want to access them by position then you should usually write your orignal JSON to use an array instead of an object.

{
    "numbers": [ "one", "two", "three", "four", "five" ]
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You can use Object.values to convert the values to an array and attach the index.

obj = {
  "numbers":{
     "firstnum":"one",
     "secondnum":"two",
     "thirdnum":"three",
     "fourthnum":"four",
     "fifthnum":"five"
  }
}

console.log(Object.values(obj.numbers)[3])
imvain2
  • 15,480
  • 1
  • 16
  • 21
0

After you parse JSON it became Object, so

const obj = {
  "numbers": {
     "firstnum":"one",
     "secondnum":"two",
     "thirdnum":"three",
     "fourthnum":"four",
     "fifthnum":"five"
  }
};

console.log(obj.numbers[Object.keys(obj.numbers)[2]]);
tarkh
  • 2,424
  • 1
  • 9
  • 12