Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

344
Vistas
Get JSON value with key in dot notation as text in JS

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.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda