简体   繁体   中英

How to convert normal JS array to JSON Object

My current array is like

['service1', 'service2', 'service3']

and I need to convert it into like

[
  {'id':'1', 'serviceName':'service1'},
  {'id':'2', 'serviceName':'service2'},
  {'id':'2', 'serviceName':'service3'}
]

Thanks in advance guys.

let arr = ['service1', 'service2', 'service3'];
arr.map((item, index) => { return {id: index + 1, serviceName: item} });
var arr = ['service1', 'service2', 'service3'];

console.log(arr.map((value, index) => {
    return {
        id: index + 1,
        serviceName: value
    };
}));

Array.prototype.map will walk over each element and modify as per your requirement and then changes the string to object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM