var data5 = [{ label: '1', children: [{ label: '2', children: [{ label: '2-1' }, { label: '2-2' }] }, { label: '3', children: [{ label: '3-1' }, { label: '3-2' }] }] }]; function dfs(list, level=1) { list.forEach(item => { if(item.children) dfs(item.children, level+1) item.level = level; }) return list; } console.log(dfs(data5))