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.
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.
Yes. @thedz: data. PropertyD needs to know the property name, which isn't dynamic enough.
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.
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.
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  
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With