You need to enable JavaScript to run this app. 如何在JavaScript中将对象转为对象数组而非二维数组
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将对象转为对象数组而非二维数组

实现方案

直接组合Object.entries()和Array.prototype.map()即可实现,代码简洁高效:

const foo = {
    A: {
        id: 1231,
        f1: "Asdasd",
        f2: [1, 2]    
    },
    B: {
        id: 2324,
        f1: "Asdasd",
        f2: [1, 2]    
    }
}

// 转换逻辑
const bar = Object.entries(foo).map(([key, value]) => ({
    "some key name": key,
    ...value
}))

代码说明

  • Object.entries(foo)会将输入对象转换为[ ['A', {id:1231,...}], ['B', {id:2324,...}] ]格式的二维数组
  • map遍历过程中解构出每一组键值对,返回新对象时将原对象的键赋值给你自定义的some key name字段,原对象的值的所有属性通过扩展运算符...展开合并到新对象中

如果运行环境不支持对象扩展运算符,可以用Object.assign实现兼容:

const bar = Object.entries(foo).map(([key, value]) => 
    Object.assign({"some key name": key}, value)
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 18:54:03