Skip to content

Instantly share code, notes, and snippets.

@maslenkov
Created December 25, 2015 12:43
Show Gist options
  • Save maslenkov/bc2a183494e2c6e76098 to your computer and use it in GitHub Desktop.
Save maslenkov/bc2a183494e2c6e76098 to your computer and use it in GitHub Desktop.
recursively find attribute in js
function find_attr(obj, name) {
var k
for(k in obj) {
if(k == name) {
return k
} else if(typeof(obj[k]) == 'object') {
path = find_attr(obj[k], name)
if(path) {
console.log(k + '/' + path)
return (k + '/' + path)
} else {
// return false
}
} else {
// return false
}
}
}
function find_attr(obj, regexp) {
var k
for(k in obj) {
if(k.match(regexp)) {
return k
} else if(typeof(obj[k]) == 'object') {
path = find_attr(obj[k], regexp)
if(path) {
console.log(k + '/' + path)
return (k + '/' + path)
} else {
// return false
}
} else {
// return false
}
}
}
{
a: 2,
b: 3,
g: {
c: 4,
d: {
e: 5
},
f: {
h: 6
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment