在嵌套数组中查找多个元素

时间:2019-06-04 05:46:00

标签: javascript recursion tree nested

我需要在嵌套数组中找到多个元素并将其作为数组返回。

我使用reduce函数来查找元素,但它仅返回一条记录。

嵌套数组:

{
    "type": "group",
    "level": 0,
    "expand": "-closed",
    "selected": false,
    "text": "Федулов Владислав Владиславович",
    "phoneNumber": "+7 (927) 999 9999",
    "email": "qweeqwe@mail.ru",
    "id": 24,
    "parent": null,
    "cardType": 0,
    "childrens": [
      {
        "type": "group",
        "level": 1,
        "expand": "-closed",
        "selected": false,
        "text": "Ширяев Феликс Богуславович",
        "phoneNumber": "+7 (123) 456 7810",
        "email": "test@test.ru",
        "id": 47,
        "parent": 24,
        "cardType": 0,
        "childrens": [
          {
            "type": "manager",
            "level": 2,
            "expand": "-empty",
            "selected": false,
            "text": "Колесова Анастасия Олеговна",
            "phoneNumber": "+7 (900) 000 0001",
            "email": "eprosvirina@baccasoft.ru",
            "id": 58,
            "parent": 47,
            "cardType": 0,
            "childrens": null
          }
        ]
      }
    ]
  },
  {
    "type": "group",
    "level": 0,
    "expand": "-closed",
    "selected": false,
    "text": "Игнатьева Женевьева Павловна",
    "phoneNumber": "+7 (777) 777 7777",
    "email": "igp@sks.ru",
    "id": 3,
    "parent": null,
    "cardType": 0,
    "childrens": [
      {
        "type": "group",
        "level": 1,
        "expand": "-closed",
        "selected": false,
        "text": "Меретин Викентий Васильевич",
        "phoneNumber": "+7 (917) 193 5222",
        "email": "keshman@gmail.com",
        "id": 2,
        "parent": 3,
        "cardType": 1,
        "childrens": [
          {
            "type": "manager",
            "level": 2,
            "expand": "-empty",
            "selected": false,
            "text": "Климаков Алексей Александрович",
            "phoneNumber": "+7 (903) 888 8888",
            "email": "krenog@gmail.com",
            "id": 20,
            "parent": 2,
            "cardType": 1,
            "childrens": null
          }
        ]
      }
    ]
  }

reduce函数:

    var array = store.managersTree.treeNodes;
    var items = [];

    const findItemNested = (arr, searchString, nestingKey) => (
    arr.reduce((a, item) => {
         if (a) return a;
         if (item.text.indexOf(searchString)!==-1 || 
             item.phoneNumber.indexOf(searchString)!==-1 || 
             item.email.indexOf(searchString)!==-1) return item;
         if (item[nestingKey]) return findItemNested(item[nestingKey], 
       searchString, nestingKey)
    }, [])
    );

    const element = findItemNested(array, searchString, "childrens");

我试图找到一条至少与一个条件匹配的记录,期望reduce返回多条记录,尽管找到了多条记录,但它仅返回一条记录。

任何帮助将不胜感激。

UPD:searchString可以是phoneNumbertextemail之类的字符串

3 个答案:

答案 0 :(得分:1)

您可以递归reduce数组。

  • Destructure参数reduce中的对象分别获取nestingKey和其他属性
  • 创建一个filterKeys数组,其中包含要搜索的searchString键。
  • 使用some检查对象中的任何字段的值是否为searchString的{​​{3}}。
  • 如果存在nestingKey,则可以将嵌套的项目推入累加器数组。

const input=[{"type":"group","level":0,"expand":"-closed","selected":false,"text":"Федулов Владислав Владиславович","phoneNumber":"+7 (927) 999 9999","email":"qweeqwe@mail.ru","id":24,"parent":null,"cardType":0,"childrens":[{"type":"group","level":1,"expand":"-closed","selected":false,"text":"Ширяев Феликс Богуславович","phoneNumber":"+7 (123) 456 7810","email":"test@test.ru","id":47,"parent":24,"cardType":0,"childrens":[{"type":"manager","level":2,"expand":"-empty","selected":false,"text":"Колесова Анастасия Олеговна","phoneNumber":"+7 (900) 000 0001","email":"eprosvirina@baccasoft.ru","id":58,"parent":47,"cardType":0,"childrens":null}]}]},{"type":"group","level":0,"expand":"-closed","selected":false,"text":"Игнатьева Женевьева Павловна","phoneNumber":"+7 (777) 777 7777","email":"igp@sks.ru","id":3,"parent":null,"cardType":0,"childrens":[{"type":"group","level":1,"expand":"-closed","selected":false,"text":"Меретин Викентий Васильевич","phoneNumber":"+7 (917) 193 5222","email":"keshman@gmail.com","id":2,"parent":3,"cardType":1,"childrens":[{"type":"manager","level":2,"expand":"-empty","selected":false,"text":"Климаков Алексей Александрович","phoneNumber":"+7 (903) 888 8888","email":"krenog@gmail.com","id":20,"parent":2,"cardType":1,"childrens":null}]}]}],
    filterKeys = ["text", "phoneNumber", "email"];

function findItemNested(array, searchString, nestingKey) {
  return array.reduce((acc, { [nestingKey]: nested, ...o }) => {
    if (filterKeys.some(k => o[k] && o[k].includes(searchString)))
      acc.push(o)
      
    if (nested)
      acc.push(...findItemNested(nested, searchString, nestingKey)) 
      
    return acc;
  }, [])
}

console.log(findItemNested(input, "keshman", "childrens"))
console.log(findItemNested(input, "@gmail.com", "childrens"))

答案 1 :(得分:0)

在处理数组中的每个元素后,始终Array.reduce返回单个值。如果要返回数组中的匹配记录,则可以使用Array.filter

[1,2,3,4,5].filter((element) => {
    return (element === 2 || element ===4);
});

对于上面的代码,过滤后的数组将是

[2,4]

在filter之前,您应该对数组进行展平或遍历每个元素以对数组进行过滤,而不要使用Array.filter()

答案 2 :(得分:0)

在不降低可能性的情况下

      col1 col2 col3
0  01/01/10  abc  pqr
1  10/10/18  sps  ggg
3  03/12/19  rt   sd