1

I have a few simple objects defined...

var objectOne = {
    settings: {
        name: "object one"
    }
}

var objectTwo = {
    settings: {
        name: "object two"
    }
}

Now let's pretend I got object from a parameter in the URL - it comes in as a string...

var obj = "objectTwo";

How can I access objectTwo.settings using this obj variable?

I can't do the below because obj is a string:

var settings1 = obj.settings;
var settings2 = [obj].settings; // also doesn't work

I tried stripping the quotes without any luck.

How can I access a top level object using a string?

3
  • 4
    If it is in the global namespace you could use window[obj].settings. Commented Jun 16, 2016 at 22:14
  • 1
    ^ That's about it. The only other way to access a variable using a string is using eval but there's almost never a good reason to do that. Commented Jun 16, 2016 at 22:16
  • I can't believe I forgot about window. Hah. So simple. Thank you! Commented Jun 16, 2016 at 22:20

3 Answers 3

2

window is a neat trick, but could you possibly change your data stricture?

var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
}

var id = "objectOne";
alert(objects[id].settings.name);
Sign up to request clarification or add additional context in comments.

Comments

1

If it is in the global namespace you could use window[obj].settings.

If not, I don't think there is much you can do except eval as @MikeC mentioned in comments, which is rarely a good idea.

Comments

1

Good question. Let's invent an Object method to access the object properties dynamically. Object.prototype.getNestedValue() Regardless how deeply your property is located, it takes a series of arguments in order and gets the desired value for you;

In this particular case it's just one argument;

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var objects = {
  objectOne: {
    settings: {
        name: "object one"
    }
  },
  objectTwo: {
    settings: {
        name: "object two"
    }
  }
},
        obj = "objectTwo";
     result = objects.getNestedValue(obj);
console.log(JSON.stringify(result));

You can see getNestedValue() and it's twin setNestedValue() working at here

1 Comment

I think you need to make it clearer in your explanation that you've changed the OP's variable definitions to make them properties of a master object.

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.