Lodash递归查找数组中的项目。

12
在lodash中,递归查找数组中基于'text'字段且值为'Item-1-5-2'的项可能是最简单的解决方案是什么?
const data = [
      {
        id: 1,
        text: 'Item-1',
        children: [
          { id: 11, text: 'Item-1-1' },
          { id: 12, text: 'Item-1-2' },
          { id: 13, text: 'Item-1-3' },
          { id: 14, text: 'Item-1-4' },
          {
            id: 15,
            text: 'Item-1-5',
            children: [
              { id: 151, text: 'Item-1-5-1' },
              { id: 152, text: 'Item-1-5-2' },
              { id: 153, text: 'Item-1-5-3' },
            ]
          },
        ]
      },
      {
        id: 2,
        text: 'Item-2',
        children: [
          { id: 21, text: 'Item-2-1' },
          { id: 22, text: 'Item-2-2' },
          { id: 23, text: 'Item-2-3' },
          { id: 24, text: 'Item-2-4' },
          { id: 25, text: 'Item-2-5' },
        ]
      },
      { id: 3, text: 'Item-3' },
      { id: 4, text: 'Item-4' },
      { id: 5, text: 'Item-5' },
    ];

谢谢!

2个回答

16

在纯Javascript中,你可以递归使用 Array#some

function getObject(array, key, value) {
    var o;
    array.some(function iter(a) {
        if (a[key] === value) {
            o = a;
            return true;
        }
        return Array.isArray(a.children) && a.children.some(iter);
    });
    return o;
}

var data = [{ id: 1, text: 'Item-1', children: [{ id: 11, text: 'Item-1-1' }, { id: 12, text: 'Item-1-2' }, { id: 13, text: 'Item-1-3' }, { id: 14, text: 'Item-1-4' }, { id: 15, text: 'Item-1-5', children: [{ id: 151, text: 'Item-1-5-1' }, { id: 152, text: 'Item-1-5-2' }, { id: 153, text: 'Item-1-5-3' }, ] }, ] }, { id: 2, text: 'Item-2', children: [{ id: 21, text: 'Item-2-1' }, { id: 22, text: 'Item-2-2' }, { id: 23, text: 'Item-2-3' }, { id: 24, text: 'Item-2-4' }, { id: 25, text: 'Item-2-5' }, ] }, { id: 3, text: 'Item-3' }, { id: 4, text: 'Item-4' }, { id: 5, text: 'Item-5' }, ];

console.log(getObject(data, 'text', 'Item-1-5-2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
@Blowsie,一个调用相同函数的函数... 请看iter. - Nina Scholz
确切地说,getObject不会调用getObject,因此不是递归的。 - Blowsie
4
但是 iter 命令会执行此操作。 - Nina Scholz

7

这是递归函数的完美应用场景。

function findText(items, text) {
  if (!items) { return; }

  for (const item of items) {
    // Test current object
    if (item.text === text) { return item; }

    // Test children recursively
    const child = findText(item.children, text);
    if (child) { return child; }
  }
}

这也是获得最大性能的最佳方法。遍历是一种深度优先搜索方式。


这个可以运行。谢谢 :) - jathri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接