0

I have the following JSON.

let carStr = `{
  "_id": "Tesla-200",
  "Design": {
    "Wheel": "Black",
    "Seat": "4",
    "Speed": "200"
  }
}`;
let car = JSON.parse(carStr);


let key = "Design.Wheel";


let keys = key.split(".");
let value = car[keys[0]][keys[1]]; // Need to get this value dynamically rather than hard-coding
console.log(value);

The key is input from another section. How do get the value "Black" by passing the key "Design.Wheel" as text dynamically.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79

1 Answers1

5

If the problem is the length of the key string is dynamic, then use reduce and access the value at every stage:

let carStr = `{
  "_id": "Tesla-200",
  "Design": {
    "Wheel": "Black",
    "Seat": "4",
    "Speed": "200"
  }
}`;
let car = JSON.parse(carStr);

let key = "Design.Wheel";
let keys = key.split(".");

let value = keys.reduce((a, c) => a[c], car);

console.log(value);

key = "Design.Seat";
keys = key.split(".");

value = keys.reduce((a, c) => a[c], car);

console.log(value);

key = "_id";
keys = key.split(".");

value = keys.reduce((a, c) => a[c], car);

console.log(value);

This should work as long as you're always starting from the root (i.e. the first property is always directly accessible as car.prop1.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79