【问题标题】:How to convert Array of Array of Objects to an Array of Arrays in Angular?如何在 Angular 中将对象数组转换为数组数组?
【发布时间】:2022-07-09 00:35:39
【问题描述】:
[[{ id: 26, type: "Source", name: "Email" }], [{ id: 27, type: "Source", name: "Id" }, { id: 29, type: "Divider", name: "+" }, { id: 30, type: "Source", name: "SupplierId" }], [{ id: 28, type: "Source", name: "CommunityId" }]

如何将上面的对象数组转换为这样的数组数组,其中“名称”被挑出?

[["Email"],["Id","+", "SupplierId"],["CommunityId"]]

我已经尝试过像这样映射它:

this.exportColumns = columns.flatMap(obj => obj.sourceColumn).map(obj => obj?.name);

但我得到了这个结果:

[ "Email", "Id", "+", "SupplierId", "CommunityId" ]

【问题讨论】:

  • 如果你不是maps/flatMap/mergeMap的高手,你可以尝试先用普通的旧循环编写它,然后用RxJS操作符替换它们

标签: javascript arrays angular typescript object


【解决方案1】:

在第一层数组中使用第二张地图

data.map(item => item.map(i => i.name));

【讨论】:

  • 如果项目是object 而不是array
【解决方案2】:

这是我实现输出的方法。

const d = [
  [{ id: 26, type: "Source", name: "Email" }], 
  [{ id: 27, type: "Source", name: "Id" }, { id: 29, type: "Divider", name: "+" }, { id: 30, type: "Source", name: "SupplierId" }],
  [{ id: 28, type: "Source", name: "CommunityId" }]
]

const newArr = d.reduce((prev, curr) => {
  if(Array.isArray(curr)) {
    prev.push(curr.map((p) => p.name))
  } else {
    prev.push(curr.name)
    // or use this if you want array
    // prev.push([curr.name])
  }
  return prev;
}, [])

console.log(newArr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多