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

JavaScript问题:对象数组转指定格式数组出错,求排查

对象数组转指定格式数组的问题

输入数据

report: [
  {"name":"abc","age":23,"gender":"male"},
  {"name":"def","age":24,"gender":"female"},
  {"name":"ghi","age":25,"gender":"other"}
]

期望输出

[["abc",23,"male"],["def",24,"female"],["ghi",25,"other"]]

编写的代码

resultArray: any = [];

report.forEach(d => {
  var energy = Object.values(d).join(",");
  this.resultArray.push([energy]);
});

实际输出

[["abc,23,male"],["def,24,female"],["ghi,25,other"]]


问题分析与解决

问题根源

你用join(",")把Object.values(d)返回的数组转成了单个字符串,之后又把这个字符串塞进新数组里,导致每个子数组只有一个拼接后的字符串元素,和预期的多元素数组结构不符。

正确写法

直接将Object.values(d)返回的数组推入结果即可,不需要拼接字符串:

resultArray: any = [];

report.forEach(d => {
  this.resultArray.push(Object.values(d));
});

更简洁的写法可以用map方法一步生成目标数组:

const resultArray = report.map(item => Object.values(item));

Object.values(item)会直接提取对象的所有属性值形成数组(比如["abc",23,"male"]),把这个数组直接加入结果,就能得到你想要的嵌套数组结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:50:25