Created
June 29, 2016 04:33
-
-
Save prettycode/5366e7ffb7cbb32dfecc02c1068b6069 to your computer and use it in GitHub Desktop.
Given an object, returns a list of property paths that can be used with lodash's _.get()
This file contains hidden or 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
function discoverPropertyPaths(parentObject, parentPath) { | |
var paths = [], | |
propertyNames = Object.keys(parentObject); | |
propertyNames.forEach(function (propertyName) { | |
var propertyPath = (parentPath ? (parentPath + '.') : '') + propertyName, | |
property = parentObject[propertyName]; | |
if (typeof property === 'object') { | |
var isArray = angular.isArray(property); | |
paths.push({ | |
id: propertyPath, | |
type: isArray ? 'array' : 'object' | |
}); | |
if (isArray) { | |
property = property[0]; | |
propertyPath += '[]'; | |
} | |
[].push.apply(paths, discoverPropertyPaths(property, propertyPath)); | |
} | |
else { | |
paths.push({ | |
id: propertyPath, | |
type: property | |
}); | |
} | |
}); | |
return paths; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment