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';
something.foo; // The idea is to access something.bar, getting "Foobar!"

11 comments

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

You can do it like this using Lodash get

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

@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';
// something.foo; -- 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

UPDATED

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.

Example

// 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. stackoverflow.com/questions/86513/…

@Paul Stenne 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: something.bar
  • 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';
something[foo];
// 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: quirksmode.org/js/associative.html stackoverflow.com/questions/14031368/…

@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'
};

foo.bar;
foo['bar'];

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';

foo[prop];

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()) {
    console.log(foo[prop]);
}

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

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

foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;

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:

resolve("document.body.style.width")
// 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('properties.that.do.not.exist', {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: stackoverflow.com/questions/37510640/…

@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: it.knightnet.org.uk/kb/node-js/get-properties

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

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

something[\`${foo}\`];

@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 https://www.w3schools.com/js/js_json_parse.asp

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

@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 - foo.bar
  • 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

38 Answered Questions

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

71 Answered Questions

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

19 Answered Questions

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

17 Answered Questions

[SOLVED] Is it possible to add dynamically named properties to JavaScript object?

  • 2009-07-26 09:24:39
  • Lee D
  • 524263 View
  • 643 Score
  • 17 Answer
  • Tags:   javascript

14 Answered Questions

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

  • 2009-06-11 19:55:12
  • atogle
  • 362449 View
  • 507 Score
  • 14 Answer
  • Tags:   javascript object

25 Answered Questions

[SOLVED] How does JavaScript .prototype work?

60 Answered Questions

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

10 Answered Questions

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

25 Answered Questions

[SOLVED] Iterate through object properties

41 Answered Questions

[SOLVED] Detecting an undefined object property

Sponsored Content