如何修改数组并将其转换为JSON [英] How to modify an array and convert it to JSON

查看:108
本文介绍了如何修改数组并将其转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

[ 'Item 1', 'Item 2', 'Item 3' ]

我需要最终的结果是

{ 'Item 1':true, 'Item 2':true, 'Item 3':true }

使用ES6,我对此很了解:

Using ES6 I got kinda close with this:

        let arr = [];
        for (let m of crmData.modRequired) {
            let i = m + ':true';
            arr.push(i);
        }
        modReq = JSON.stringify(arr);
        modReq = modReq.replace(/\[/, '{');
        modReq = modReq.replace(/\]/, '}');

但是产生了: {"Quotes:true","Flight Logs:true","Currency Records:true","FTD:true","Maintenance Tracker:true"}

推荐答案

使用Object.assignArray.map可以很容易地做到这一点,就像这样:

You can do this very easily with Object.assign and Array.map, like so:

这个想法是将值数组映射到遵循{"ItemX": true}模式的对象数组,然后使用Object.assign将它们组合成单个对象.

The idea is to map your array of values into an array of objects that follow the {"ItemX": true} pattern, and then combine them into a single object using Object.assign.

var items = ["Item 1", "Item 2", "Item 3"];

var mapped = Object.assign({}, ...items.map(item => ({[item]: true})));

console.log(JSON.stringify(mapped));

这篇关于如何修改数组并将其转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆