Skip to content

Instantly share code, notes, and snippets.

@oknoorap oknoorap/index.js
Last active Apr 23, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.