Last active
April 23, 2016 10:35
-
-
Save oknoorap/c4cdb6109eddb5b240c2a9ee7cab4e46 to your computer and use it in GitHub Desktop.
Javascript search nested Array of Object
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
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