2

I have an array

var subject = ["Tamil", "English", "Math"];

I need to convert it to object as follows

[{
  "name": "Tamil"
 }, {
  "name": "English"     
 }, {
  "name": "Math"
}]

2 Answers 2

4

With underscore:

const subject = ['Tamil', 'English', 'Math'];

const out = _.map(subject, el => ({ name: el }));

console.log(out);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.4/underscore-min.js"></script>

Native JS using map:

const subject = ['Tamil', 'English', 'Math'];

const out = subject.map(el => ({ name: el }));

console.log(out);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! Perfect answer for my question. I thought it can't be done using Native JavaScript. But if it is possible in Native Javascript, then it is the best to use I feel. So, accepted the above answer.
2

You can use Native JavaScript's Array.prototype.map() at this context,

var subject = ["Tamil", "English", "Math"];
subject = subject.map(function(itm){
  return {"name" : itm };
});

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.