Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Created April 6, 2012 17:40
Show Gist options
  • Save jasonrhodes/2321581 to your computer and use it in GitHub Desktop.
Save jasonrhodes/2321581 to your computer and use it in GitHub Desktop.
Get a nested object property by passing a dot notation string as the property name
/**
* A function to take a string written in dot notation style, and use it to
* find a nested object property inside of an object.
*
* Useful in a plugin or module that accepts a JSON array of objects, but
* you want to let the user specify where to find various bits of data
* inside of each custom object instead of forcing a standardized
* property list.
*
* @param String nested A dot notation style parameter reference (ie "urls.small")
* @param Object object (optional) The object to search
*
* @return the value of the property in question
*/
function getProperty( propertyName, object ) {
var parts = propertyName.split( "." ),
length = parts.length,
i,
property = object || this;
for ( i = 0; i < length; i++ ) {
property = property[parts[i]];
}
return property;
}
@Hbahmani
Copy link

hi dudes

@Hbahmani
Copy link

is there anybody help me about angular 6?

@Hbahmani
Copy link

@laxa88 Hi

@my3sons
Copy link

my3sons commented Sep 10, 2018

I tried 10 other examples before this that all failed miserably, yours worked like a charm, thanks!

@jumpjack
Copy link

How can I get this working for something like obj->geometry[6]->obs[3]->latitude ?

@mp2468
Copy link

mp2468 commented Dec 27, 2019

Would anyone know how to do this to handle array as well? like being able to do
myVal = getDescendantProp(myData, 'someProperty.deeperProperty[0].evendeeperproperty');

@DavChi
Copy link

DavChi commented Apr 21, 2020

@mp2468 Based on this, we could use regex to handle both dot notation and bracket notation path.

const getDescendantProp = (obj, path) => {
  const arr = path.split(/[.[]['"]?/);
  let o = obj;
  while (arr.length && o) {
    o = o[arr.shift().replace(/['"]?]$/, '')];
  }
  return o;
};

@kissu
Copy link

kissu commented Jan 7, 2021

A functional answer might be (es2015 just because):

const getDescendantProp = (obj, path) => (
    path.split('.').reduce((acc, part) => acc && acc[part], obj)
);

Damn man, it doesn't even error if the path is not valid (no optional chaining needed), L33T. Thanks ! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment