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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.