javascript - 如何在 JavaScript 中获取无限嵌套数组中的父 ID

标签 javascript

如题,但我遇到了一个问题!

我想创建 getParentId(array, id) 函数。

此函数通过子id获取父id。

const array = [{
  id: 1,
  title: 'hello',
  children: [{
    id: 3,
    title: 'hello',
    children: [{
      id: 4,
      title:'hello',
      children: [
        { id: 5, title: 'hello'},
        { id: 6, title: 'hello'}
      ]
    },
    {
      id: 7,
      title: 'hello'
    }]
  }]
},
{
  id: 2,
  title: 'hello',
  children: [
    { id: 8, title: 'hello'}
  ]
}]
  • 这个数组可以无限嵌套

预期结果:

getParentId(array, 3) -> 1

getParentId(array, 5) -> 4

getParentId(array, 6) -> 4

getParentId(array, 8) -> 2

getParentId(array, 2) -> null

如果你能给我发送信息,我将不胜感激。

最佳答案

您可以通过迭代实际数组及其子数组并在找到 id 时停止来采用递归方法。

function getParentId(array, id, parentId = null) {
    return array.some(o => {
        if (o.id === id) return true;
        const temp = getParentId(o.children || [], id, o.id);
        if (temp !== null) {
            parentId = temp;
            return true;
        }
    })
        ? parentId
        : null;
}

const array = [{ id: 1, title: 'hello', children: [{ id: 3, title: 'hello', children: [{ id: 4, title:'hello', children: [{ id: 5, title: 'hello' }, { id: 6, title: 'hello' }] }, { id: 7, title: 'hello' }] }] }, { id: 2, title: 'hello', children: [{ id: 8, title: 'hello' }] }];

console.log(getParentId(array, 3)); // 1
console.log(getParentId(array, 5)); // 4
console.log(getParentId(array, 6)); // 4
console.log(getParentId(array, 8)); // 2
console.log(getParentId(array, 2)); // null
console.log(getParentId(array, 7)); // 3
console.log(getParentId(array, 4)); // 3
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在 JavaScript 中获取无限嵌套数组中的父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896719/

相关文章:

javascript - 使用socket.io更新express实时 View

javascript - 为什么它在保存的文件中添加反斜杠?

javascript - 使用 jquery draggable/droppable 通过类定位特定的 div

Javascript - 按 ID 名称选择元素

javascript - Angular js将数据插入列表不起作用

javascript - 如何在javascript中使用if条件来处理json?

javascript - JavaScript 中的函数原型(prototype)

javascript - 我如何制作一个固定定位的侧边栏,但只有当它到达底部时

javascript - 为什么这个视频无法播放? HTML5 Canvas

javascript - react 选择多个选项