You need to enable JavaScript to run this app. JavaScript中将键值对象转换为指定结构对象数组的实现方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中将键值对象转换为指定结构对象数组的实现方法咨询

键值对象转指定结构化数组的实现方法

使用原生JavaScript的Object.entries搭配数组map方法即可快速实现,无需引入任何第三方依赖:

// 待转换的原始键值对象
const words = {
  told: 64,
  mistake: 11,
  thought: 16,
  bad: 17
}

// 转换为目标结构数组
const structuredArray = Object.entries(words).map(([text, value]) => ({ text, value }))

执行上述代码后,structuredArray的输出结果与需求完全一致:

[
  { text: 'told', value: 64 },
  { text: 'mistake', value: 11 },
  { text: 'thought', value: 16 },
  { text: 'bad', value: 17 }
]

如果需要兼容不支持Object.entries的老旧环境(如IE11及以下),可改用Object.keys实现等效逻辑:

var structuredArray = Object.keys(words).map(function(key) {
  return {
    text: key,
    value: words[key]
  }
})

注意:两种实现方式默认仅提取原始对象自身的可枚举属性,不会返回原型链上继承的属性,完全适配当前场景的转换要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 14:06:04