You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将两个对象数组转换为客户订单概览?

JavaScript 对象数组合并格式问题解决

问题场景

现有两个数组:

var customer = [
  { "Name": "Thomas", "Address": "example street 34", "customerID": 1 },
  { "Name": "Alica", "Address": "example street 24", "customerID": 2 },
  { "Name": "John", "Address": "example bouelvard 4", "customerID": 3 }
]

var orders = [
  { "Product": "iPhone 12", "Amount": 2, "customerID": 1 },
  { "Product": "charger", "Amount": 1, "customerID": 1 },
  { "Product": "screen protection", "Amount": 5, "customerID": 2 }
]

需要生成每个元素结构如下的概览数组:

{
  customer: {
    "Name": "Thomas",
    "Address": "example street 34",
    "customerID": 1,
  },
  order: [
    {
      "Product": "iPhone 12",
      "Amount": 2,
      "customerID": 1
    },
    {
      "Product": "charger",
      "Amount": 1,
      "customerID": 1
    }
  ]
}

尝试的代码(存在错误):

let overview = customers.map(element1 => ({ ...element1, : [...(orders.filter(element => element.customerID === element1.customerID))] }));

得到的结果:

{
  "Name": "Thomas",
  "Address": "example street 34",
  "customerID": 1,
  "order": [[Object], [Object]]
}

解决方法与问题解释

1. 添加customer:外层键

原代码直接展开了客户对象的属性,没有给它套上customer键。正确写法是在map回调里返回包含customer字段的对象,将当前客户元素赋值给该字段:

let overview = customer.map(element1 => ({
  customer: { ...element1 }, // 复制客户对象作为customer字段的值
  order: orders.filter(element => element.customerID === element1.customerID)
}));

注意:filter本身返回数组,无需用展开运算符再包裹一层,直接赋值给order字段即可。

2. 为什么order数组显示为[[Object], [Object]]

这是控制台的简化输出行为:当数组元素是对象时,控制台会用[Object]来简化显示,并非数组结构异常。你可以通过console.log(JSON.stringify(overview, null, 2))打印完整的JSON结构,就能看到order数组里的具体对象内容。

另外原代码还有两个小错误需要修正:

  • 变量名错误:定义的数组是customer,代码里误写为customers
  • 语法错误:对象字面量中多了一个多余的冒号(...element1, : [...处的冒号)

修正后的代码运行后,就能得到预期的结构。


内容的提问来源于stack exchange,提问作者I_hate_haskell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:55:22