Skip to content

Instantly share code, notes, and snippets.

@oknoorap
Last active April 23, 2016 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oknoorap/c4cdb6109eddb5b240c2a9ee7cab4e46 to your computer and use it in GitHub Desktop.
Save oknoorap/c4cdb6109eddb5b240c2a9ee7cab4e46 to your computer and use it in GitHub Desktop.
Javascript search nested Array of Object
var body = {
id: 'body',
elements: [{
id: 'abc',
elements: []
}, {
id: 'def',
elements: [{
id: 'ghi',
elements: [{
id: 'jkl',
elements: [{
id: 'mno',
elements: [{
id: 'xxx',
elements: []
}, {
id: 'nnn',
elements: []
}, {
id: 'dkz',
elements: [{
id: 'oop',
elements: []
}, {
id: 'uuu',
elements: []
}, {
id: 'lol',
elements: [{
id: 'yuhu',
elements: [{
id: 'mamamia',
elements: [{
id: 'xxx',
elements: []
}, {
id: 'popo',
elements: [{
id: 'el-mama',
elements: [{
id: 'endd',
elements: []
}, {
id: 'nono',
elements: [{
id: 'hahuha',
elements: []
}]
}]
}]
}]
}]
}]
}]
}]
}]
}, {
id: 'haha',
elements: []
}, {
id: 'saya',
elements: []
}]
}]
}, {
id: 'xyz'
}]
};
function findElement (root, id, fn) {
if (root.elements) {
var i = 0, len = root.elements.length
for (;i<len;i++) {
if (root.elements[i].id === id) fn && fn({parent: root, self: root.elements[i]})
else findElement(root.elements[i], id, fn);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment