javascript – lodash以递归方式查找数组中的项目

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

谢谢!

解决方法:

在普通的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,group and count