JavaScript 已知数据格式 实现一个函数 fn 找出链条中所有的父级 id
const list = [{
id: '1',
name: 'test1',
children: [
{
id: '11',
name: 'test11',
children: [
{
id: '111',
name: 'test111'
},
{
id: '112',
name: 'test112'
}
]
},
{
id: '12',
name: 'test12',
children: [
{
id: '121',
name: 'test121'
},
{
id: '122',
name: 'test122'
}
]
}
]
}];
const id = '112'
const fn = (value) => {
...
}
fn(id, list) // 输出 [1, 11, 112]
function fn(id, list) {
const match = list.find(item => item.id === id);
if (match) return [id];
const sub = list.find(item => id.startsWith(item.id));
return [sub.id].concat(fn(id, sub.children));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论