4

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
}

3
  • The parameter st data format, can it be altered? Commented Jul 28, 2016 at 15:05
  • No the data format of st can't be changed :) Commented Jul 28, 2016 at 15:08
  • I can insert " after [ and before ] also Commented Jul 28, 2016 at 15:13

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, can you please take a look at stackoverflow.com/questions/64911518/… . :(
what about setValue(st, obj, value) ?
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!

3 Comments

eval will never be the best solution unfortunately.
thats true but the question is the most unusual one I have seen
I've seen such before and even answered one: stackoverflow.com/a/13719799/1249581. Funny but I even used that code in some projects at work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.