Aditya
Aditya

Reputation: 51

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.

Upvotes: 0

Views: 41

Answers (2)

Adarsh Mohan
Adarsh Mohan

Reputation: 1384

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.

Upvotes: 1

Tatul Mkrtchyan
Tatul Mkrtchyan

Reputation: 371

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

Upvotes: 2

Related Questions