15 comments

@GavinBelson 2020-05-21 15:40:43

For anyone looking to set the value of a nested variable, here is how to do it:

const _ = require('lodash'); //import lodash module

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4

Documentation: https://lodash.com/docs/4.17.15#set

Also, documentation if you want to get a value: https://lodash.com/docs/4.17.15#get

@Luke 2020-02-25 19:19:27

I came across a case where I thought I wanted to pass the "address" of an object property as data to another function and populate the object (with AJAX), do lookup from address array, and display in that other function. I couldn't use dot notation without doing string acrobatics so I thought an array might be nice to pass instead. I ended-up doing something different anyway, but seemed related to this post.

Here's a sample of a language file object like the one I wanted data from:

const locs = {
  "audioPlayer": {
    "controls": {
      "start": "start",
      "stop": "stop"
    },
    "heading": "Use controls to start and stop audio."
  }
}

I wanted to be able to pass an array such as: ["audioPlayer", "controls", "stop"] to access the language text, "stop" in this case.

I created this little function that looks-up the "least specific" (first) address parameter, and reassigns the returned object to itself. Then it is ready to look-up the next-most-specific address parameter if one exists.

function getText(selectionArray, obj) {
  selectionArray.forEach(key => {
    obj = obj[key];
  });
  return obj;
}

usage:

/* returns 'stop' */
console.log(getText(["audioPlayer", "controls", "stop"], locs)); 

/* returns 'use controls to start and stop audio.' */
console.log(getText(["audioPlayer", "heading"], locs)); 

@Aft3rL1f3 2020-01-17 02:40:10

I asked a question that kinda duplicated on this topic a while back, and after excessive research, and seeing a lot of information missing that should be here, I feel I have something valuable to add to this older post.

  • Firstly I want to address that there are several ways to obtain the value of a property and store it in a dynamic Variable. The first most popular, and easiest way IMHO would be:
let properyValue = element.style['enter-a-property'];

however I rarely go this route because it doesn't work on property values assigned via style-sheets. To give you an example, I'll demonstrate with a bit of pseudo code.

 let elem = document.getElementById('someDiv');
 let cssProp = elem.style['width'];

Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.

  • Henceforth the getComputedStyle() method!
function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

W3Schools getComputedValue Doc This gives a good example, and lets you play with it, however, this link Mozilla CSS getComputedValue doc talks about the getComputedValue function in detail, and should be read by any aspiring developer who isn't totally clear on this subject.

  • As a side note, the getComputedValue method only gets, it does not set. This, obviously is a major downside, however there is a method that gets from CSS style-sheets, as well as sets values, though it is not standard Javascript. The JQuery method...
$(selector).css(property,value)

...does get, and does set. It is what I use, the only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery, it just makes life easy, and offers methods, like this one, which is not available with standard Javascript. Hope this helps someone!!!

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

ES5 // Check Deeply Nested Variables

This simple piece of code can check for deeply nested variable / value existence without having to check each variable along the way...

var getValue = function( s, context ){
    return Function.call( context || null, 'return ' + s )();
}

Ex. - a deeply nested array of objects:

a = [ 
    {
      b : [
          {
             a : 1,
             b : [
                 {
                    c : 1,
                    d : 2   // we want to check for this
                 }
             ]
           }
      ]
    } 
]

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

Cheers!

@Rodrigo Leite 2019-12-08 21:27:55

If the solution is to use eval, you just created a million other problems.

@user4602228 2019-12-09 13:56:50

@RodrigoLeite ok, so it wouldn't be a problem to give at least one...

@Rodrigo Leite 2019-12-10 04:43:41

@user4602228 2019-12-10 09:35:44

@RodrigoLeite I have read it, and updated the solution to use Function instead

@user4642212 2020-07-01 14:03:15

The correct approach for this in ECMAScript 2020 is using optional chaining: if(a?.[0]?.b?.[0]?.b?.[0]?.d === 2){}.

@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';
// 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/…

@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: 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

@O-9 2020-07-09 10:19:48

In TypeScipt, this works if first casted to any. (obj as any).x[foo]. Even better solution is to user Interfaces

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

@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

@Eagle1 2020-02-28 17:39:57

I love this solution. However I'm trying to modify the values in the original object, it seems your function returns a sub copy of the object. Is it possible to change it so that modifying the returned object modifies the original ?

@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

47 Answered Questions

[SOLVED] Sort array of objects by string property value

29 Answered Questions

[SOLVED] Iterate through object properties

42 Answered Questions

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

22 Answered Questions

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

25 Answered Questions

[SOLVED] How does JavaScript .prototype work?

45 Answered Questions

[SOLVED] Detecting an undefined object property

11 Answered Questions

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

18 Answered Questions

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

  • 2009-06-11 19:55:12
  • atogle
  • 474388 View
  • 622 Score
  • 18 Answer
  • Tags:   javascript object

63 Answered Questions

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

67 Answered Questions

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

Sponsored Content