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

如何用Python将JSON数组中的值提取为新键值对?

一行代码实现数组转指定键值对对象

方法1:使用reduce

const new_arr = arr.reduce((acc, cur) => ({ ...acc, [cur.id]: Number(cur.value) }), {})

遍历数组,将每个元素的id作为键,value转为数字后作为值,逐步构建目标对象。如果不需要转换数值类型,去掉Number()即可。

方法2:使用Object.fromEntries(ES2019+)

const new_arr = Object.fromEntries(arr.map(item => [item.id, Number(item.value)]))

先把原数组映射成[键, 值]格式的二维数组,再通过Object.fromEntries直接转换为目标对象,写法更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:05:17