在嵌套对象数组中查找对象(Lodash / Javascript / Typescript)

时间:2018-10-16 15:14:24

标签: javascript arrays typescript lodash

让我们说有一个如下所示的对象数组:

select s.*,
       s.sales / nullif(s_1.sales, 0) as year1_growth,
       s.sales / nullif(s_2.sales, 0) as year2_growth,
       s.sales / nullif(s_3.sales, 0) as year3_growth
from sales s left join
     sales s_1
     on s.name = s_1.name and
        strftime('%Y', s.date) = stftime('%Y', s_1.date) + 1 left join
     sales s_2
     on s.name = s_2.name and
        strftime('%Y', s.date) = stftime('%Y', s_2.date) + 2 left join
     sales s_3
     on s.name = s_3.name and
        strftime('%Y', s.date) = stftime('%Y', s_3.date) + 3;

在我的应用程序中,用户选择一个Tablerow,然后我又获得了所选的行信息,也就是 let example = [ { children: [{ data: { id: 2, group: 1001, name: "Audi" }, }], data: { id: 1, group: 1000, name: "Cars" } }, { children: [{ data: { id: 4, group: 1003, name: "Airbus A320" }, }], data: { id: 3, group: 1002, name: "Planes" } }, { children: [{ data: { id: 6, group: 1005, name: "Departed" } }], data: { id: 5, group: 1006, name: "movies" } } ] ,例如

'data' object

现在,我想使用lodash或javascript / typescript在数组中基于{ id: 2, group: 1001, name: "Audi" } 查找所选数据对象。

我将如何实现?子数组会给我带来麻烦。

编辑:还应该找到一个孩子的孩子。

Id

1 个答案:

答案 0 :(得分:1)

/** find by id data using recursion */
function findById(data, id) {
  for (const datum of data) {
    if (datum.data.id == id) return datum
    if (datum.children) {
      let result = findById(datum.children, id)
      if (result) return result
    }
  }
}


let example = [{
    children: [{
      data: {
        id: 2,
        group: 1001,
        name: "Audi"
      },
    }],
    data: {
      id: 1,
      group: 1000,
      name: "Cars"
    }
  },
  {
    children: [{
      data: {
        id: 4,
        group: 1003,
        name: "Airbus A320"
      },
    }],
    data: {
      id: 3,
      group: 1002,
      name: "Planes"
    }
  },
  {
    children: [{
      data: {
        id: 6,
        group: 1005,
        name: "Departed"
      }
    }],
    data: {
      id: 5,
      group: 1006,
      name: "movies"
    }
  }
]



console.log(findById(example, 2))