简体   繁体   中英

Dynamically access object using variable

I'm trying to access an object using a dynamic name. Is this possible?

const something = { bar: "Foobar!" };
const objectName = 'something';
const propertyName = 'bar';

[objectName][propertyName]; // The idea is to access something.bar, getting "Foobar!"

edit : I am trying to use a variable to access the object itself, not its properties

Here's one deceptively simple way to do it:

eval(objectName)[propertyName];

... which is obviously a really bad idea if you ever can lose the full control over what's stored in objectName variable (and just a bad idea otherwise, as eval code won't be optimized and controlled by your spellchecking IDE magic, for example).

Far better idea is to turn your something (and any other name you want to query) into a property of an object itself. For example:

const state = {
  something: {
    foo: 'Foobar'
  }
};

... and later access it with bracket notation :

console.log(state[objectName][propertyName]);

All the variables you declare in the browser are properties of the window object so you could actually use this.

var something = { bar: 'Foobar!' };
var objectName = 'something';
var propertyName = 'bar';

window[objectName][propertyName];

But this only works when you declare variables with var . It doesn't work for let and const .

Use this script

    var something = { bar: "Foobar!" };
    var objectName = 'something';
    var propertyName = 'bar';

    console.log(eval(objectName)[propertyName]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM