Home > Blockchain >  How to access a nested property of an object using a string?
How to access a nested property of an object using a string?

Time:07-11

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

This might get downvoted for no reason but it 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);

  • Related