Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!