【问题标题】:lodash recursively find item in arraylodash递归查找数组中的项目
【发布时间】:2016-10-06 12:52:26
【问题描述】:

在 lodash 中递归查找数组中的项目可能是最简单的解决方案,例如,通过值为 'Item-1-5-2' 的 'text' 字段?

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' },
    ];

谢谢!

【问题讨论】:

    标签: javascript recursion lodash


    【解决方案1】:

    在纯 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; }

    【讨论】:

    • @Blowsie,一个调用相同函数的函数……请看iter
    • 恰好getObject 不调用getObject 因此不是递归的。
    • iter 可以。
    【解决方案2】:

    这是递归函数的完美位置。

    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; }
      }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多