-1
const a = {"b":{"c":3}}
const z = "b.c"

I have the above values and now I want to get value 3(a.b.c) from a using the z variable. I have tried the below method but it is not working

  • a.z
  • ${a.z}
  • ${a[z]}
  • ...etc..
Benk I
  • 185
  • 13

3 Answers3

2

You can do something like this

function rGetAttr(obj, dotPath){
  return dotPath.split('.').reduce((o,i)=> o[i], obj)
}

const obj = {a: {b: {c: 123}}}
console.log(rGetAttr(obj, "a.b.c"))
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
1

You can do it by using Lodash


const _ = require("lodash");

console.log(_.get(a, z));
kiran
  • 444
  • 3
  • 15
0

You could do something like this:

const a = {
  "b": {
    "c": 3
  }
}

const keyName = "b";

// This works to access an objects elements by key name
console.log(a[keyName]);

// If you want to be able to have "b.c" then you need to handle the nesting something like this:
const getValue = (obj, prop) => {
    const parts = prop.split('.');
    let thisObj = obj;
    let part = 0;
    while (thisObj = thisObj?.[parts[part++]]) {
        if (part >= parts.length) break;
    }
    return thisObj;
}


const nestedKeyName = "b.c";
// Usage like this:
console.log(getValue(a, nestedKeyName));
Dutchman
  • 183
  • 1
  • 11