Dinesh Ramasamy
Dinesh Ramasamy

Reputation: 994

How to convert array to object in underscore?

I have an array

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

I need to convert it to object as follows

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

Upvotes: 2

Views: 1618

Answers (2)

Andy
Andy

Reputation: 63524

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);

Upvotes: 4

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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 };
});

Upvotes: 2

Related Questions