1

Example:

var v1 = "['a']";
var v2 = "['b']['c']";
var obj = {a: 'a', b: {c: "['b']['c']"}};

Is it possible to use 'v1' or 'v2' like a method for 'obj'? I need it for API because I do not know what should I parse. It can be obj['a'] or obj['b']['c']. Any solutions?

2
  • 1
    No, that's not possible. You need to know the full path of the key you're looking for. Consider flattening the structure or using an ES6 Map. Commented Jan 11, 2016 at 13:22
  • You could extend obj with a function that takes a string as a parameter (i.e. v1, v2) and then parses it. Commented Jan 11, 2016 at 14:04

1 Answer 1

1

Here's an example of what I was talking about, extending your object with a function that parses the string input and looks up the corresponding element.

A big caveat here is that I was lazy about handling of quotations, so you'll need to fiddle it a bit to handle single and double quotes. I haven't extensively tested, but I think it will return undefined when there's no match in the object.

var v1 = "['a']";
var v2 = "['b']['c']";
var obj = {
  getByStr: function(str) {
    var args = str.replace("['", '').replace(new RegExp("'\]" + '$'), '').split("']['");
    var match = this[args.shift()];
    while(match !== undefined && args.length > 0)
      match = match[args.shift()];
    return match;
  },
  a: 'a',
  b: {
    c: "['b']['c']"
  }
};

document.write('v1 -- ' + obj.getByStr(v1) + '<br />');
document.write('v2 -- ' + obj.getByStr(v2) + '<br />');

If you think you might use it, but there's anything you don't understand in there, post a comment and I'll add some clarifications.

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.