Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda