Home > OS >  How to ready dynamic key value from object in js
How to ready dynamic key value from object in js

Time:02-16

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..

CodePudding user response:

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"))

CodePudding user response:

You can do it by using Lodash


const _ = require("lodash");

console.log(_.get(a, z));

CodePudding user response:

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));

CodePudding user response:

There is no support for qualified "selectors"/property chains like that in plain JS.

I've got a solution for you, but it's something I'd not ever use personally.

const accessToProperty = `a.${z}` // will produce `a.b.c`
eval(accessToProperty ) // evaluates the string as JS code, i.e. get c prop of b prop of a obj

However, there are Reasons Why You Should Never Use eval() in JavaScript.

The safer and saner variant would be parsing z with split, and then recursively obtaining the property like @anjaneyulubatta505's answer

  • Related