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

如何将字符串数组转换为各键值为true的JSON对象字符串

数组转指定格式JSON字符串实现方案

你可以先将源数组转换为符合结构要求的对象,再调用JSON.stringify()方法生成JSON字符串即可,以下是两种常用的实现方式:

  • 方法1:使用reduce方法(简洁写法,推荐)
const originArr = ['Role1', 'Role2', 'Role3'];
// 遍历数组生成目标对象
const targetObj = originArr.reduce((accumulator, currentKey) => {
  accumulator[currentKey] = true;
  return accumulator;
}, {});
// 转换为JSON字符串
const result = JSON.stringify(targetObj);

上述代码最终输出的result即为你需要的格式的JSON字符串。

  • 方法2:使用基础for循环实现(兼容性更好)
const originArr = ['Role1', 'Role2', 'Role3'];
const targetObj = {};
for(let i = 0; i < originArr.length; i++) {
  const currentKey = originArr[i];
  targetObj[currentKey] = true;
}
const result = JSON.stringify(targetObj);

两种实现逻辑本质都是遍历数组的每一项,把数组元素作为对象的键,对应赋值为布尔值true,最后再做JSON序列化即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:24:01