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

223
Vistas
How to use variables in dot notation like square bracket notation with variable depth

How can I access different JSON objects in JavaScript by a variable containing the attribute's path?

var item = {
              "car": {
                 "manufacturer": "Ford",
                 "model": "Taunus"
                 "surface": {
                     "color": "silver",
                     "type": "metallic"
                 }
                 "built (year)": "1975"
           };

let foo = "model";
let bar = "surface.color";

consloe.log("Model: " + item[foo]);          // Output: "Taunus"
console.log("Surface color:" + item[bar]);   // Output: "undefined", Desired output "silver"

This notation represents only one hierarchic level per set of brackets, of course. Is there an easy elegant way to access several levels with only one labeling variable like "one.two" and "one.two.three"?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can create a function that will split the string with . (dot) as the delimiter into an array of strings, and use them to traverse the object in a reducer function.

const item = {
  "car": {
    "manufacturer": "Ford",
    "model": "Taunus",
    "surface": {
        "color": "silver",
        "type": "metallic"
    },
    "built (year)": "1975"
  }
}

const foo = "car.model";
const bar = "car.surface.color";

function get(path) {
  const parts = path.split(".");
  return parts.reduce((obj, part) => obj[part], item);
}  

get(foo); // should return "Taunus"
get(bar); // should return "silver"
about 4 years ago · Juan Pablo Isaza 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