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

JavaScript中如何使用map()方法将数组转换为指定结构的嵌套对象

问题分析

你写的代码无法达到预期有两个核心原因:

  • Array.map() 本身只能返回新数组,无法直接生成你需要的对象结构
  • 你的回调函数仅修改了原数组元素的std属性,没有返回构造目标结构需要的内容,也没有处理std字段的非数字后缀提取逻辑

实现方案

如果你必须使用map()方法完成,可以先生成键值对数组,再通过Object.fromEntries()转为目标对象,代码如下:

let a =[{"name":"test","age":12,"std":"1std"},{"name":"test2","age":14,"std":"2nd"}, {"name":"test3","age":11,"std":"3rd"}];

const result = Object.fromEntries(
  a.map(stu => {
    // 提取std字段中的数字作为对象的键
    const objKey = stu.std.match(/\d+/)[0];
    // 构造键值对,同时把age转为字符串匹配你给出的输出格式
    return [objKey, {name: stu.name, age: String(stu.age)}];
  })
);

console.log(result);

运行后result就是你需要的目标结构。

补充说明

如果不限制必须用map(),更简洁的方案是直接用Array.reduce()生成对象:

const result = a.reduce((acc, stu) => {
  const objKey = stu.std.match(/\d+/)[0];
  acc[objKey] = {name: stu.name, age: String(stu.age)};
  return acc;
}, {});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:03:01