Last active
August 8, 2016 21:40
-
-
Save jdnichollsc/a60896beda77073c2e2b8358baf3eb7c to your computer and use it in GitHub Desktop.
Accesing Nested Object Properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var assignProperty = function (object, property, value) { | |
if (typeof property === "string") { | |
property = property.split("."); | |
} | |
if (property.length > 1) { | |
var e = property.shift(); | |
assignProperty(object[e] = Object.prototype.toString.call(object[e]) === "[object Object]" ? object[e] : {}, property, value); | |
} else { | |
object[property[0]] = value; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var findProperties = function(item, parentProperty){ | |
var properties = []; | |
for (property in item) { | |
if (item.hasOwnProperty(property)){ | |
var propertyName = [parentProperty, property].filter(Boolean).join('.'); | |
if(typeof item[property] !== 'object') { | |
properties.push(propertyName); | |
} | |
else{ | |
properties = properties.concat(findProperties(item[property], propertyName)); | |
} | |
} | |
} | |
return properties; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Derived from http://blog.nicohaemhouts.com/2015/08/03/accessing-nested-javascript-objects-with-string-key/ | |
var getNested = function (theObject, path, separator) { | |
try { | |
separator = separator || '.'; | |
return path. | |
replace(/\[/gi, separator).replace(/\]/gi, ''). | |
split(separator). | |
reduce( | |
function (obj, property) { | |
return obj[property]; | |
}, theObject | |
); | |
} catch (err) { | |
return undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment