0

Consider the following JSON object:

{
    "data": {
        "data2": {
            "myProp": "hello"
        }
    }
}

I need to be able to dynamically access the deep property myProp, but the catch is, that I need to be able to write the deep property as a regular string. i.e:

let sortByThisValue = 'data.data2.myProp'

So I already started:

let propertyArray = sortByThisValue.split('.')
//Do something here
let myVal = data.[data2][myProp] //Or data.data2.myProp 
Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50

1 Answers1

1

You can access like below

const obj = {
  data: {
    data2: {
      myProp: "hello",
    },
  },
};

const key = "data.data2.myProp";

const getValue = (obj, key) => {
  const keys = key.split(".");
  let value = obj;
  for (let i = 0; i < keys.length; i++) {
    value = value[keys[i]];
    if (!value) {
       break;
    }
  }
  return value;
};


console.log(getValue(obj, key));
console.log(getValue(obj, 'abc'));
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37