javascript - 迭代对象数组以合并新对象

标签 javascript angular typescript lodash

我正在尝试用数组创建新对象。我已经使用 lodash map 进行了尝试。但我的问题是如何获取特定集合中的 product_ids 并将其放入数组中。

这是对象

[
  [
    {
      "id": "b7079be6-c9ab-4d24-9a1d-38eddde926c2",
      "collection": "mortgages",
      "product_id": "854174665132787596022"
    },
    {
      "id": "0da12779-6fe9-45d5-afbf-91d2466e5b7e",
      "collection": "mortgages",
      "product_id": "304285269353822734222"
    },
    {
      "id": "87a137ba-5f66-4e94-8d5d-698dfbaa08ec",
      "collection": "mortgages",
      "product_id": "-304414504724243127922"
    }
  ],
  [
    {
      "id": "522f4b83-4c5a-4ffe-836d-33a51325d251",
      "collection": "carinsurance",
      "product_id": "10413803"
    },
    {
      "id": "02b79566-9cf7-48fa-a8d3-eecf951b5a76",
      "collection": "carinsurance",
      "product_id": "10397803"
    }
  ]
]

我已经试过这段代码了

map(this.products, (item, key) => {
   this.arr.push({
      collection: item[0].collection,
      product_ids: item.product_id
   });
});

我想要这样的结果。

{
    "collection": "mortgages",
    "product_ids": [
        "304285269353822734222",
        "854174665132787596022",
        "-304414504724243127922"
    ]
},
{
    "collection": "carinsurance",
    "product_ids": [
        "10413803",
        "10397803"
    ]
}

但我得到了这个结果。谁能帮我解决这个问题。

{
    "collection": "mortgages",
    "product_ids": undefined
},
{
    "collection": "carinsurance",
    "product_ids": undefined
}

最佳答案

item在你的情况下是一个数组,但你正在访问它,就好像有一个 product_id数组本身的字段,你必须映射所有 product_id数组中每个项目的属性:

map(this.products, (item, key) => {
   return {
      collection: item[0].collection,
      product_ids: item.map(i => i.product_id)
   };
});

此外,如果 map 函数返回一个数组,对于初始数组中的每个项目,它会将其转换为新格式,因此您可以返回并分配给 this.arr而不是推送到 this.arr在 map 函数中。

关于javascript - 迭代对象数组以合并新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386513/

相关文章:

javascript - 对托管在单独服务器上的 WebAPI 的 Ajax GET 请求出现错误

html - 将 HTML 传递到我的组件中

javascript - TS2741 类型 '{ 标签 : string; } Javascript 中缺少属性 '0'

Typescript 泛型循环遍历对象数组并与它们相交

javascript - React map 更改索引号并破坏条件渲染

javascript - 将 +1 附加到电话号码字段值

javascript - Angular2 Typescript如何从对象内部检索数组

通用 "promisify"函数中的 Typescript 类型推断

javascript - 在 d3 中从 v3 转换为 v5 不会更新可视化,但会添加另一个可视化

angular - 如何从未映射到路由/路由器导出的组件访问 Angular 2.0 中的路由参数