1

I have a object like

var obj = {
  floorPlan: 'hello',
  dateSpan: {
    from: Sat Feb 21 2015 00: 00: 00 GMT + 0530(IST),
    to: Wed Feb 25 2015 00: 00: 00 GMT + 0530(IST)
  }
};

and a string

var a = 'dateSpan.to';

I want to access 'obj.dateSpan.to' using the variable 'a'. How can I do it? please help.

2
  • var a = obj.dateSpan.to; ??? Commented Jan 16, 2015 at 6:45
  • suppose to access obj.floorPlan i can use obj['floorPlan']. Similarly i want to access obj.dateSpan.to Commented Jan 16, 2015 at 6:56

1 Answer 1

1

You will need to split the string by . character and loop through the object until you reach the last part of the split string:

function getValue(str) {
    var val = obj,
        parts = str.split('.');
    while (val[parts[0]]) {
        val = val[parts.shift()]
    }
    return parts.length == 0 ? val : null;
}


var obj = {
    floorPlan: 'hello',
    dateSpan: {
        from: "Sat Feb 21 2015 00: 00: 00 GMT + 0530(IST)",
        to: "Wed Feb 25 2015 00: 00: 00 GMT + 0530(IST)"
    }
};

var a = 'dateSpan.to';

alert(getValue(a));

Sign up to request clarification or add additional context in comments.

Comments

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.