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

如何用JavaScript将对象嵌套结构重构为目标JSON数组格式?

解决方案

这里给你写一段简洁的JavaScript代码,正好用Object.entries()来处理你的数据转换需求:

const originalData = {"1245": {"case_id": "1245", "nodes": 11, "others": {"hops": "1"}, "status": "COMPLETE"}};

const transformedData = {
  data: Object.entries(originalData).map(([key, value]) => {
    // 解构外层属性和others里的属性,合并成新对象
    const { others, ...rest } = value;
    return { ...rest, ...others, hops: Number(others.hops) }; // 把hops转成数字类型
  })
};

console.log(transformedData);

代码细节解释:

  • Object.entries(originalData):把原始对象转换成键值对数组,这里得到的是[["1245", {...}]]这样的结构,方便遍历处理每个case。
  • map()方法遍历每个键值对:
    • 用解构赋值{ others, ...rest }把value里的others单独拆分出来,剩下的核心属性(case_id、nodes、status)存在rest里。
    • 用扩展运算符...rest和...others合并两层属性,同时把hops从字符串类型转为数字,完全匹配你要的目标格式。

运行这段代码后,输出结果就是你期望的结构:

{
  "data": [
    {
      "case_id": "1245",
      "nodes": 11,
      "status": "COMPLETE",
      "hops": 1
    }
  ]
}

如果后续原始数据里有多个case(比如多组键值对),这段代码也能自动批量处理,把每个case都转换成data数组里的独立对象,适配性很强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:27:30