如何将字符串数组转换为各键值为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
相关产品推荐
相关产品推荐

