By RichW

2010-11-22 11:23:32 8 Comments

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

const something = { bar: "Foobar!" };
const foo = 'bar';; // The idea is to access, getting "Foobar!"


@BartusZak 2019-10-04 14:49:41

There is a few possibilities:

const test = {
    prop1: {
      prop2: {
        prop3: "I'm very nested"

const test1 = test.prop1.prop2.prop3
const test2 = test['prop1']['prop2']['prop3']
const test3 = test['prop1.prop2.prop3'] //will return undefined
const test4 = _.get(test, 'prop1.prop2.prop3') //use lodash

If you want to get nested value dynamically (e.g. by variable), your best option will be to use lodash.

@levi 2019-08-21 07:09:13

For example :

a = [ {b:[{a:1,b:[{c:1,d:2}]}]} ]

Instead of :

if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 )  // true

We can now :

if( getValue('a[0].b[0].b[0].d') == 2 ) // true

Here is the code

 * @method getValue
 * @description simplifies checking for existance and getting a deeply nested value within a ceratin context
 * @argument {string} s       string representation of the full path to the requested property 
 * @argument {object} context optional - the context to check defaults to window
 * @returns the value if valid and set, returns undefined if invalid / not available etc.
var getValue = function( s, context ){
    var fn = function(){
            return eval(s);
            return undefined;

@shalonteoh 2018-09-06 06:36:15

You can do it like this using Lodash get

_.get(object, 'a[0].b.c');

@Jonathan Kempf 2019-06-27 19:51:57

There are many situations, such as deep nested object lookups, where this is the only option.

@Rupesh Agrawal 2018-07-31 08:24:07

Whenever you need to access property dynamically you have to use square bracket for accessing property not "." operator
Syntax: object[propery}

const something = { bar: "Foobar!" };
const foo = 'bar';
//; -- not correct way at it is expecting foo as proprty in  something={ foo: "value"};
// correct way is  something[foo]
alert( something[foo])

@Mr Br 2015-06-22 08:10:25


I have take comments below into consideration and agreed. Eval is to be avoided.

Accessing root properties in object is easily achieved with obj[variable], but getting nested complicates thing. Not to write already written code I suggest to use lodash.get.


// Accessing root property
var rootProp = 'rootPropert';
_.get(object, rootProp, defaultValue);

// Accessing nested property
var listOfNestedProperties = [var1, var2];
_.get(object, listOfNestedProperties);

Lodash get can be used on different ways, here is link to the documentation lodash.get

@Luke 2015-06-23 18:07:53

It's best to avoid using eval whenever possible.…

@Kyll 2015-10-23 10:14:34

Using eval for something as trivial as accessing properties is plain overkill and hardly advisable under any circumstance. What's "trouble"? obj['nested']['test'] works very well and doesn't require you to embed code in strings.

@Mr Br 2015-10-23 12:27:11

Question is how to access property dynamically, and you have given example where you use everything static. Give me example how can you access 3d level child dynamically simpler (with no overkill) and I will delete my answer.

@jaggedsoft 2015-11-26 01:25:45

eval is three times slower or more, I wouldn't recommend this to newbies because it might teach them bad habits. I use obj['nested']['value'] - remember kids, eval is evil!

@iPherian 2015-12-29 01:51:50

For the record, eval is slow but there's no security issue with eval in this example.

@doug65536 2016-10-01 18:58:35

@MrBr You use square bracket notation when you have a variable which has the name. var key = isFullMoon() ? 'werewolf' : 'human', personState = state[key]; If isFullMoon() returns true, it puts state.werewolf into personState, otherwise it puts state.human into personState, assuming state has a human property and a werewolf property. Of course, this example is necessarily oversimplified, in more realistic code, key is more unpredictable/dynamic.

@Emile Bergeron 2016-12-20 21:42:15

@Luke He's now the only want to bring Lodash _.get to the table. I think this answer deserves now upvotes instead of downvotes. It may be overkill, but it's good to know it exists.

@TPHughes 2018-07-03 09:03:54

Thank you for introducing lodash for this. I came here by google looking for a method to set a value deep in an object, and used their _.set method (which is identical to above but with the extra arguement for the value to set).

@Jan Hančič 2010-11-22 11:25:44

There are two ways to access properties of an object:

  • Dot notation:
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected

@chacham15 2011-12-06 08:40:12

careful with this: javascript compilers will error here since they dont rename strings but they do rename object properties

@Sudhanshu Mishra 2014-06-03 09:00:03

Some more info on why this is possible: JS objects are associative arrays, that's why. Further Reading:…

@Vanquished Wombat 2017-01-03 16:01:11

@dotnetguy No they are not. Arrays are objects that inherit from the plain JS object prototype and therefore you can add properties a go-go like any plain object. The 'associative' behaviour is more object-like than array like. You can't iterate the 'associative' version by simple index so it is not displaying array-like behaviour. You can define your 'associative' array as {} or [] and treat it the same in either case as far as random property access is concerned.

@Sudhanshu Mishra 2017-01-06 00:30:23

@VanquishedWombat Not sure what your objection pertains to? I did not say that JS Objects are arrays?

@youhana 2017-06-08 21:23:10

as a reference to the correct answer , Reference

@jgritten 2018-01-25 23:14:20

Is it possible to take this further and get a property of an object that is a property of my base object? I have a 'car' object and I want to know the drivers name. my car has a property of Driver. that driver object has a name property. ie. car['Driver.Name']? <- this doesn work for me. thanks

@Jan Hančič 2018-02-08 15:11:08

@jgritten simply do car.Driver.Name

@Vittal ks 2019-05-22 06:03:45

When use to access properties using bracket notation its tslist issue throwing warning Generic Object Injection Sink security/detect-object-injection

@Gorka Hernandez 2017-03-08 11:30:43

You can achieve this in quite a few different ways.

let foo = {
    bar: 'Hello World'

The bracket notation is specially powerful as it let's you access a property based on a variable:

let foo = {
    bar: 'Hello World'

let prop = 'bar';


This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'

for (let prop in foo.getOwnPropertyNames()) {

Both dot and bracket notation also work as expected for nested objects:

let foo = {
    bar: {
        baz: 'Hello World'

Object destructuring

We could also consider object destructuring as a means to access a property in an object, but as follows:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'

let prop = 'last';
let { bar, baz, [prop]: customName } = foo;

// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'

@abahet 2017-07-26 08:57:15

This is my solution:

function resolve(path, obj) {
    return path.split('.').reduce(function(prev, curr) {
        return prev ? prev[curr] : null
    }, obj || self)

Usage examples:

// or
resolve("style.width", document.body)
// or even use array indexes
// (someObject has been defined in the question)
resolve("part.0.size", someObject) 
// returns null when intermediate properties are not defined:
resolve('', {hello:'world'})

@Moby Disk 2017-12-15 14:06:49

This is similar to lodash get

@Julian Knight 2019-01-03 13:45:20

Excellent answer, see also:…

@Julian Knight 2019-01-03 14:04:56

You inspired me to create an enhanced version that allows bracket notation & property names with spaces as well as validating the inputs:

@Sergey 2017-07-02 19:04:31

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


@Ilmari Karonen 2017-09-19 18:49:35

Why on earth would you do that? Your foo is already a string, so `${foo}` is exactly the same as foo. (Also, your code seems to have some extra backslashes that don't belong there. But it would still be pointless even if you fixed that syntax error.)

@zloctb 2016-08-02 19:46:41

Following is an ES6 example of how you can access the property of an object using a property name that has been dynamically generated by concatenating two strings.

var suffix = " name";

var person = {
    ["first" + suffix]: "Nicholas",
    ["last" + suffix]: "Zakas"

console.log(person["first name"]);      // "Nicholas"
console.log(person["last name"]);       // "Zakas"

This is called computed property names

@onmyway133 2017-06-14 21:42:51

You should use JSON.parse, take a look at

const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')

@Jacksonkr 2016-11-13 17:37:21

It gets interesting when you have to pass parameters to this function as well.

Code jsfiddle

var obj = {method:function(p1,p2,p3){console.log("method:",arguments)}}

var str = "method('p1', 'p2', 'p3');"

var match = str.match(/^\s*(\S+)\((.*)\);\s*$/);

var func = match[1]
var parameters = match[2].split(',');
for(var i = 0; i < parameters.length; ++i) {
  // clean up param begninning
    parameters[i] = parameters[i].replace(/^\s*['"]?/,'');
  // clean up param end
  parameters[i] = parameters[i].replace(/['"]?\s*$/,'');

obj[func](parameters); // sends parameters as array
obj[func].apply(this, parameters); // sends parameters as individual values

@Sonique 2014-07-01 15:40:39

In javascript we can access with:

  • dot notation -
  • square brackets - foo[someVar] or foo["string"]

But only second case allows to access properties dynamically:

var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}

var name = "pName"
var num  = 1;

foo[name + num]; // 1

// -- 

var a = 2;
var b = 1;
var c = "foo";

foo[name + a][b][c]; // bar

@Chad 2018-06-07 14:28:20

I'm staring at 2,000 lines of if statements because the previous dev didn't use square brackets, and statically accessed object properties by dot notation. It's for an approval process app that has 7 different approvers and the steps are all the same. /rip

Related Questions

Sponsored Content

42 Answered Questions

[SOLVED] Sort array of objects by string property value

41 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

60 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

28 Answered Questions

[SOLVED] Iterate through object properties

20 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

  • 2009-07-08 13:21:32
  • Adam Ernst
  • 1801580 View
  • 2734 Score
  • 20 Answer
  • Tags:   javascript object

42 Answered Questions

[SOLVED] Detecting an undefined object property

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

25 Answered Questions

[SOLVED] How does JavaScript .prototype work?

16 Answered Questions

[SOLVED] How to access the first property of an object in Javascript?

  • 2009-06-11 19:55:12
  • atogle
  • 415120 View
  • 564 Score
  • 16 Answer
  • Tags:   javascript object

10 Answered Questions

[SOLVED] How to access the correct `this` inside a callback?

Sponsored Content