3

I want a method in javascript that gets a string as its arguments and return a value from a nested object like as:

var obj = {
  place: {
    cuntry: 'Iran',
    city: 'Tehran',
    block: 68,
    info: {
     name :'Saeid',
      age: 22
    }
  }
};

function getValue(st) {
  // st: 'place[info][name]'
  return obj['place']['info']['name'] // or obj.place.info.name
}
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
SAlidadi
  • 85
  • 10

2 Answers2

3

One possible solution for your use case:

function getValue(st, obj) {
    return st.replace(/\[([^\]]+)]/g, '.$1').split('.').reduce(function(o, p) { 
        return o[p];
    }, obj);
}

console.log( getValue('place[info][name]', obj) );  // "Saeid"
console.log( getValue('place.info.age', obj) );     // 22
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Hi, can you please take a look at https://stackoverflow.com/questions/64911518/access-nested-object-with-n-level-deep-object-using-square-bracket-notation . :( – Samuel Nov 19 '20 at 13:38
1

Can you get your input in the form of "['a']['b']['c']"?

function getValue(st) {
  // st: "['place']['info']['name']"
  return eval("obj"+st);
}

You can apply transformation to any strings and get the result.

EDIT:

DO NOT Use Eval directly in your code base. Its evil!

footy
  • 5,803
  • 13
  • 48
  • 96