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

276
Views
How to access a nested property of an object using a string?

I have the following string:

const str = "prop1.prop2.prop3"

I want to use this string to access the property prop3 of the following object:

const obj = {
   prop1: {
      prop2:{
         prop3:{
            // ---- destination point
         }
      }
   }
}

But I'm not able to figure out how to do it? there must be something that keeps adding the obj[currentProp] so on and so on. and.. isn't there a quicker method? I'm afraid I'm wasting my time on something that can be achieved more easily

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This would be my approach:

const access = (path, object) => {
  return path.split('.').reduce((o, i) => o[i], object)
}

const obj = {
  prop1: {
    prop2: {
      prop3: {
        value: 'foo'
      }
    }
  }
}

const str = 'prop1.prop2.prop3'

console.log(access(str, obj)) // {"value": "foo"}
about 4 years ago · Juan Pablo Isaza Report

0

different ways to access a nested property of an object

using a function accessDeepProp with two arguments the object and path of the nested property!

Recursive way:

function accessDeepProp(obj, path) {
  if (!path) return obj;
  const properties = path.split(".");
  return accessDeepProp(obj[properties.shift()], properties.join("."));
}

For-loop way:

function accessDeepProp(obj, path) {
  const properties = path.split(".");
  for (let i = 0; i < properties.length; i++) {
    if (!obj) return null;
    obj = obj[properties[i]];
  }
  return obj;
}

Eval way: never_use_eval!

function accessDeepProp(objName, path) {
  try {
    return eval(`${objName}.${path}`);
  } catch (e) {
    return null;
  }
}

you could also use lodash get method

about 4 years ago · Juan Pablo Isaza Report

0

You can combine split with forEach as follows:

const str = "prop1.prop2.prop3"

const obj = {
   prop1: {
      prop2:{
         prop3:{
            a: "b",
            c: "d"
         }
      }
   }
}

var srch = obj;

str.split(".").forEach(item => (srch = srch[item]));

console.log(srch); // { a: "b", c: "d"}
console.log(obj);

split converts str's value into an array, which is then looped and on each iteration, srch gets one level deeper.

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!