collect children of array in javascript code example
Example 1: find array with children javascript
const find = (array = [], id) => {
for (const item of array) {
const result = item.id === id ? item : find(item.children, id);
if(result) return result;
}
};
const commentList = [{ id: 1, text: 'A', children: [{ id: 2, text: 'B' }] }, { id: 4, text: 'asd', children: [] }, { id: 5, text: 'vx', children: [{ id: 7, text: 'xxss' }] }, { id: 8, text: 'ghfdh', children: [{ id: 15, text: 'I want to take this' }] }, { id: 10, text: 'A', children: [{ id: 18, text: 'Bsda' }] }];
const result = find(commentList, 15);
console.log(result);
Example 2: children array javascript
var foo = document.getElementById('foo');
for (var i = 0; i < foo.children.length; i++) {
console.log(foo.children[i].tagName);
}