Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript how can I dynamically get a nested property of an object

var arr = { foo : 1, bar: { baz : 2 }, bee : 3 }  function getter(variable) {   return arr[variable]; } 

If I want 'foo' vs 'bee' I can just do arr[variable] - that's easy, and the function does that.

But what if I want to get arr.bar.baz AKA arr[bar][baz]?

What can I pass to the getter function that will let me do that, (and of course also let me get non-nested properties using the same function).

I tried getter('bar.baz') and getter('[bar][baz]') but those didn't work.

I suppose I can parse for dots or brackets (like here: In javascript, test for property deeply nested in object graph?). Is there a cleaner way? (Besides eval of course.)

Especially because I need to get the deeply set properly many many times in a loop for a bunch of array elements.

like image 406
Ariel Avatar asked Aug 02 '11 00:08

Ariel


People also ask

How do I access nested objects?

To access a nested attribute, you need to specify its name and then search through the object. When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required.

Can we add dynamically named properties to JavaScript object?

Yes. @thedz: data. PropertyD needs to know the property name, which isn't dynamic enough.

What is nested object in JavaScript?

The basic definition of an object in JavaScript is a container for named values called properties (keys). Sometimes, we need to create an object inside another object. In this case, it's called a nested object.


2 Answers

You can use a deep access function based on a string for the path. Note that you can't have any periods in the property names.

function getPropByString(obj, propString) {   if (!propString)     return obj;    var prop, props = propString.split('.');    for (var i = 0, iLen = props.length - 1; i < iLen; i++) {     prop = props[i];      var candidate = obj[prop];     if (candidate !== undefined) {       obj = candidate;     } else {       break;     }   }   return obj[props[i]]; }  var obj = {   foo: {     bar: {       baz: 'x'     }   } };  console.log(getPropByString(obj, 'foo.bar.baz')); // x console.log(getPropByString(obj, 'foo.bar.baz.buk')); // undefined

If the access string is empty, returns the object. Otherwise, keeps going along access path until second last accessor. If that's an ojbect, returns the last object[accessor] value. Otherwise, returns undefined.

like image 136
RobG Avatar answered Oct 20 '22 14:10

RobG


Using ES6:

var arr = { foo : 1, bar: { baz : 2 }, bee : 3 }; var {foo, bar, bar: {baz}, bee} = arr; 

Same as:

// var foo = 1; // var bar = {baz: 2}; // var baz = 2; // var bee = 3; 

Using lodash: https://lodash.com/docs#get

_.get(arr, 'bar.baz'); //returns 2; _.get(arr, 'bar.baz[5].bazzz'); //returns undefined wont throw error; _.get(arr, 'bar.baz[5].bazzz', 'defaultvalue'); // Returns defaultValue because result is undefined  
like image 26
Ninja Avatar answered Oct 20 '22 13:10

Ninja