Traverse array of objects recursively in JavaScript
const getNames = (t, result) => { if(t.children.length === 0) { result.push(t.name); return result; } result.push(t.name); for(let i =0; i < t.children.length ; i++) { getNames(t.children[i], result); } return result; } const tree = { name: 'Joe', children: [ { name: 'Jenny', children: [] }, { name: 'Cathy', children: [ { name: 'Ane', children: [] }, { name: 'Clara', children: [] } ] } ] } console.log(getNames(tree, [])); // Output: // ['Joe', 'Jenny', 'Cathy', 'Ane', 'Clara']