0

Here is how one conventionally gets a value from a json object:

var random_json_string = "{ "name": "YOLO"}";
var value = JSON.parse(random_json_string);

var key = value.name; // key is now "YOLO"

But I want to do this :

var keyTitle = "name";
var random_json_string = "{ "name": "YOLO"}";
    var value = JSON.parse(random_json_string);

    var key = value.keyTitle; // I cannot do this because the code tries to search the json object for a child with the name ketTitle instead of searching for the child with the name : "name"

Notice on the last line I want to search for the key with the name that is defined by the var keyTitle.

How do we do this?

Naman Jain
  • 321
  • 5
  • 21

1 Answers1

2

You'll have to use a computed property, like so:

var keyTitle = "name";
var random_json_string = `{ "name": "YOLO"}`;
var value = JSON.parse(random_json_string);

var key = value[keyTitle];

console.log(key)
Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
  • How about the case where suppose var keyTitle = "name.lastname", and my json object has a key that has a key. I tried to do var key = value[keyTitle] for this case but it didn't work out for me. – Naman Jain Apr 23 '20 at 16:59
  • `console.log()` the `keyTitle` and see what value it's getting. – Luís Ramalho Apr 23 '20 at 22:52