javascript - lodash递归查找数组中的项目

标签 javascript recursion lodash

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 中,您可以使用 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; }

关于javascript - lodash递归查找数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896537/

相关文章:

c++ - 每个斐波那契数的递归调用次数

无需循环查询的类别和子类别的 PHP 树结构

javascript - 根据第二个数组中的值过滤对象数组

javascript - 保存 Canvas 像素或状态以供以后使用的更快方法是什么?

javascript - localstorage.setitem 不适用于 Angular

javascript - Google 地理编码异步方法中的 Firebase 更新

javascript - lodash 中如何删除整个 memoize 缓存?

javascript - 输入字段在reactjs中不可编辑

Python 递归行为

javascript - 如何检测多级对象是否具有未定义或 null 属性?