在多维数组中搜索项目

Search item in multidimensional array

我正在处理树节点,我想创建一个函数来按 ID 查找项目。

获得它的最佳和最佳解决方案是什么?

我认为这将是一个递归函数,但我不确定,我需要帮助,请选择我将使用什么来解决这个问题:)

这是我的例子:

const treeData = [
  {
    title: 'parent 1',
    key: 11,
    children: [
      {
        title: 'parent 1-0',
        key: 12,
       
        children: [
          {
            title: 'leaf',
            key: 13,
            
            children: [
              {
                title: 'leaf111',
                key: 14,
               
              },
              {
                title: 'leaf',
                key: 15,
              },
            ],
          },
          {
            title: 'leaf666',
            key:88,
          },
        ],
      },
      {
        title: 'parent 1-1',
        key: 55,
        children: [
          {
            title: (
              <span
                style={{
                  color: '#1890ff',
                }}
              >
                sss
              </span>
            ),
            key: '0-0-1-0',
          },
        ],
      },
    ],
  },
];

输入:14

输出:{title: 'leaf111',key: 14},

我们可以创建一个重复函数:

  • 遍历数组中的每个对象并
    • Returns id 匹配的对象
    • 用对象 children 调用自己

const treeData = [{title: 'parent 1', key: 11, children: [{title: 'parent 1-0', key: 12, children: [{title: 'leaf', key: 13, children: [{title: 'leaf111', key: 14, }, {title: 'leaf', key: 15, }, ], }, {title: 'leaf666', key:88, }, ], }, {title: 'parent 1-1', key: 55, children: [{title: '(<span style={{color: \'#1890ff\', }} > sss </span> )', key: '0-0-1-0', }, ], }, ], }, ];

const findById = (e, id) => {
    for (let o of e) {
        return (o.key == id) ? o : findById(o.children, id);
    }
}

const res = findById(treeData, 14);
console.log(res);

输出:

{
  "title": "leaf111",
  "key": 14
}

您可以使用树遍历器,它遍历树并在访问每个节点时调用提供的函数。提供的函数可以检查节点是否与提供的 ID 匹配。

一个例子:

function getNodeById(id) {
  let matchingNode;
  walk(tree, node => {
    if(node.key === 14) {
       matchingNode = node;
    }
  });
  return matchingNode;
}

正如您提到的,可以使用递归实现树遍历器。在从最顶层节点开始的预排序操作中,walker 获取树(根节点)并在每次调用时:

  • 用当前节点调用回调函数
  • 对于每个子节点,用子节点和回调调用自身
function walker(node, cb) {
  cb(node);
  if (Array.isArray(node.children)) {
    node.children.forEach(child => walker(child, cb));
  }
}

为了与 React 一起使用,您可以使用 React.Children.forEach, or you may prefer try a library like https://github.com/FormidableLabs/react-ssr-prepass 实现自己的行走。