Home > Enterprise >  How to get object property dynamically using a custom function
How to get object property dynamically using a custom function

Time:10-22

I have a funciton that accept a property name

func(propertyName) {
  return object[propertyName];
}

so by calling func('value') will return the object.value

However the object is complex, so it has inner props

What I want to do is to be able to do that func('property1.property2')

What is the best way to do that?

CodePudding user response:

You can pass the inner object like in the sample below:

function getVal(obj, propertyName) {
  if (obj){
     return obj[propertyName];
  }
}

var o = { 
          prop1: {
            prop2: {
              prop3: 'john'
       }
}};

console.log(getVal(o.prop1.prop2, 'prop3'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you just want to reference an inner property, you can protect from getting null exception using the optional chaining operator (?.)

const x = {prop1: {prop2: 'john'}};
console.log(x?.prop1?.prop2?.prop3?.prop4); //undefined instead of error
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

optional chaining operator- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

CodePudding user response:

try this:

example data: a={b:{c:"hellooo"}};

function: function getValue(object,propertyName){ return propertyName.split(".").reduce((a,c)=>a[c],object); }

response:

getValue(a,"b.c") = hellooo

CodePudding user response:

function getValueByKeyPath(obj, path) {
  return String(path)
    .split('.')
    .reduce((value, key) => value?.[key], Object(obj))
}

const sampleData = {
  foo: {
    value: 'foo',
    bar: {
      value: 'bar',
      baz: {
        value: 'baz',
      },
    },
  },
};

console.log(
  "getValueByKeyPath(sampleData, 'foo.bar.baz.value') ...",
  getValueByKeyPath(sampleData, 'foo.bar.baz.value')
);
console.log(
  "fail safe ... getValueByKeyPath(sampleData, 'foo.biz.baz.value') ...",
  getValueByKeyPath(sampleData, 'foo.biz.baz.value')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related