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

JavaScript如何将对象数组转换为指定属性值为键值的对象数组

数组对象按指定字段转换为键值对对象数组

你需要的转换逻辑可以直接通过数组map方法实现,遍历每个元素时动态构造新对象即可。

示例对照

  • 输入:
[
  {'size': '56 X 56 X 190', 'no_of_ups': 5},
  {'size': '65 X 55 X 110', 'no_of_ups': 2}
]
  • 输出:
[
  {'56 X 56 X 190': 5},
  {'65 X 55 X 110': 2}
]

实现代码

现代JS(ES6+)写法

利用计算属性名语法可以快速完成单元素转换:

const input = [{'size': '56 X 56 X 190', 'no_of_ups': 5}, {'size': '65 X 55 X 110', 'no_of_ups': 2}];
const output = input.map(item => ({ [item.size]: item.no_of_ups }));

兼容旧环境写法

如果运行环境不支持ES6语法,先创建空对象再动态添加属性即可:

var input = [{'size': '56 X 56 X 190', 'no_of_ups': 5}, {'size': '65 X 55 X 110', 'no_of_ups': 2}];
var output = input.map(function(item) {
  var obj = {};
  obj[item.size] = item.no_of_ups;
  return obj;
});

说明

这个方案是通用的:如果后续需要更换映射的字段,比如把id作为键、count作为值,只需要把代码里取值的item.size和item.no_of_ups替换成对应的字段取值即可,整体遍历逻辑不需要调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:39:45