0

Trying access a deep object props with a predefined variable name.I see the result as undefined. Can someone please suggest best way to handle it

const testObject = {
      a :{
        b: {
          c: 'hello'
        }
      }
    }
    
    const testCol = "a.b.c"
    
    console.log(testObject.testCol)
Nagesh
  • 121
  • 11

1 Answers1

1

Unsure if this is the best solution. You can split testCol by . to get an array of each individual key you're trying to access. Then, use the .reduce() with object bracket notation to try and access each individual property at a time.

const testObject = {
    a :{
        b: {
          c: 'hello'
        }
    }
}
    
const testCol = "a.b.c"
const keys = testCol.split('.');

const result = keys.reduce((obj, key) => {
  if (obj && obj.hasOwnProperty(key)) {
    return obj[key];
  }
  
  return undefined;
}, testObject);

console.log(result);
Elitezen
  • 6,551
  • 6
  • 15
  • 29