Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

enter 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading