You need to enable JavaScript to run this app. JavaScript如何遍历单键对象数组生成指定名称的嵌套对象
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何遍历单键对象数组生成指定名称的嵌套对象

JavaScript 单键对象数组合并实现

核心逻辑

  • 遍历原数组所有元素,每个元素都是仅含单个键值对的对象
  • 提取每个元素自带的键和值,直接写入合并对象,不使用数组索引作为键名,从根源避免出现0、1、2这类数字键
  • 最终将合并对象挂载到自定义的photo_type属性下

实现代码

方法1:reduce 简洁写法

let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]

const result = {
  photo_type: arr.reduce((mergedObj, currentItem) => {
    const [key, value] = Object.entries(currentItem)[0]
    mergedObj[key] = value
    return mergedObj
  }, {})
}

方法2:forEach 易读写法

let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]

const photo_type = {}
arr.forEach(item => {
  const [key, value] = Object.entries(item)[0]
  photo_type[key] = value
})

const result = { photo_type }

最终输出结构

两种方法执行后,得到的result完全匹配目标结构:

{
  "photo_type": {
    "Personal": "1000",
    "sport": "2100",
    "Industrial": "1200",
    "Commercial": "2300",
    "Fashion": "1300",
    "Documentary": "2600"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 10:36:08