通过 id 查找深度嵌套的对象

恰霍夫斯基

我需要通过 id 在深度嵌套的对象中查找名称。也许lodash会有所帮助?如果我不知道我的数组中有多少嵌套对象,那么最干净的方法是什么?

这是示例数组:

let x = [
   {
        'id': '1',
        'name': 'name1',
        'children': []
    },
    {
        'id': '2',
        'name': 'name2',
        'children': [{
                'id': '2.1',
                'name': 'name2.1',
                'children': []
            },
            {
                'id': '2.2',
                'name': 'name2.2',
                'children': [{
                        'id': '2.2.1',
                        'name': 'name2.2.1'
                    },
                    {
                        'id': '2.2.2',
                        'name': 'name2.2.2'
                    }
                ]
            }
        ]
    },
    {
        'id': '3',
        'name': 'name3',
        'children': [{
                'id': '3.1',
                'name': 'name3.1',
                'children': []
            },
            {
                'id': '3.2',
                'name': 'name3.2',
                'children': []
            }
        ]
    }
];

例如,我有 id “2.2”,我需要它的名称。谢谢

阿德里安·德佩雷蒂

从您的数据来看,这是一个可以帮助您轻松实现这一目标的解决方案

function findById(array, id) {
  for (const item of array) {
    if (item.id === id) return item;
    if (item.children?.length) {
      const innerResult = findById(item.children, id);
      if (innerResult) return innerResult;
    }
  }
}

const foundItem = findById(x, "2.2");
console.log(foundItem);
/*
    The result obtained here is: {id: '2.2', name: 'name2.2', children: Array(2)}
*/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章