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

125
Views
How can I access object properties using an array of strings / keys?

Let us consider the following array and object:

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

Naturally, I would access the data like so:

object['a']['b']['c']

The question is, how can I access the data using the array as input? Something like:

object[...keys]
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Probably no other way to do this

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

console.log(getValue(object, ...keys))

function getValue(obj, ...keys) {
  let current = obj
  for (const key of keys) {
    current = current[key]
  }
  return current
}

about 4 years ago · Santiago Trujillo Report

0

You can loop through the keys:

function getValueAtObjectPath(obj, path) {
  let val = obj;
  let key = path.shift();
  while(key && val) {
    val = val[key];
    key = path.shift();
  };
  return val;
}

const keys = ['a', 'b', 'c'];

const object = {
  a: {
    b: {
      c: {
        data: 1
      }
    }
  }
}

let val = getValueAtObjectPath(object, keys);
console.log('value at object path: ' + JSON.stringify(val));

Return:

value at object path: {"data":1}
about 4 years ago · Santiago Trujillo 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!