Skip to content

Instantly share code, notes, and snippets.

@andresmatasuarez
Created July 13, 2015 01:34
Show Gist options
  • Save andresmatasuarez/32716742df0ab00c3ad2 to your computer and use it in GitHub Desktop.
Save andresmatasuarez/32716742df0ab00c3ad2 to your computer and use it in GitHub Desktop.
JavaScript | findNested | Find a property by its name deeply in an object (without knowing its level).
# Based on: http://stackoverflow.com/questions/15642494/find-property-by-name-in-a-deep-object
findNested = (obj, key, memo) ->
proto = Object.prototype
ts = proto.toString
'[object Array]' != ts.call(memo) and (memo = [])
for own k, v of obj
if k == key
memo.push v
else if '[object Array]' == ts.call(v) or '[object Object]' == ts.call(v)
scope.findNested v, key, memo
memo
// From: http://stackoverflow.com/questions/15642494/find-property-by-name-in-a-deep-object
function findNested(obj, key, memo) {
var i, proto = Object.prototype, ts = proto.toString;
('[object Array]' !== ts.call(memo)) && (memo = []);
for (i in obj) {
if (proto.hasOwnProperty.call(obj, i)) {
if (i === key) {
memo.push(obj[i]);
} else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
findNested(obj[i], key, memo);
}
}
}
return memo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment