Created
July 13, 2015 01:34
-
-
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).
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
# 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 |
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
// 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