0

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.

1
  • Try this : const arr2=arr1.map(function(ele,index){return{'id':index+1,'servicename':ele};});console.log(arr2); Commented Mar 9, 2021 at 17:19

2 Answers 2

2
let arr = ['service1', 'service2', 'service3'];
arr.map((item, index) => { return {id: index + 1, serviceName: item} });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Tatul, this is exactly what I am looking for.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.