简体   繁体   中英

How to access 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

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

different ways to access a nested property of an object

using a function accessDeepProp with two arguments the object and path of the nested property!

Recursive way:

function accessDeepProp(obj, path) {
  if (!path) return obj;
  const properties = path.split(".");
  return accessDeepProp(obj[properties.shift()], properties.join("."));
}

For-loop way:

function accessDeepProp(obj, path) {
  const properties = path.split(".");
  for (let i = 0; i < properties.length; i++) {
    if (!obj) return null;
    obj = obj[properties[i]];
  }
  return obj;
}

Eval way: never_use_eval!

function accessDeepProp(objName, path) {
  try {
    return eval(`${objName}.${path}`);
  } catch (e) {
    return null;
  }
}

you could also use lodash get method

You can combine split with forEach as follows:

 const str = "prop1.prop2.prop3" const obj = { prop1: { prop2:{ prop3:{ a: "b", c: "d" } } } } var srch = obj; str.split(".").forEach(item => (srch = srch[item])); console.log(srch); // { a: "b", c: "d"} console.log(obj);

split converts str 's value into an array, which is then looped and on each iteration, srch gets one level deeper.

This is the shortest solution, and it supports arrays and ['bracket notation']. Just don't run it against malicious user input.

Update: a better(?) version without eval .

 const obj = { prop1: { prop2: { prop3: { value: 'foo' } } } } const str = 'prop1.prop2.prop3' //console.log(eval("obj." + str)) // a code without eval var value = (Function("return obj." + str))(); console.log(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM