Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to add property to each element in an array

How can I using lodash, with minimum code transform an array like this:

['Alfa','Betta','Gamma','Delta']

into:

[
 { squad: 'Alfa'},
 { squad: 'Betta'},
 { squad: 'Gamma'},
 { squad: 'Delta'},
]
like image 621
iLemming Avatar asked Jan 23 '14 21:01

iLemming


1 Answers

In Lo-Dash (or Underscore):

_.map(['Alpha', 'Beta', 'Gamma', 'Delta'], function (squad) {
    return { squad: squad };
});

In ES5:

['Alpha', 'Beta', 'Gamma', 'Delta'].map(function (squad) {
    return { squad: squad };
});

In ES2015:

['Alpha', 'Beta', 'Gamma', 'Delta'].map(squad => ({ squad }));
like image 58
Pavlo Avatar answered Oct 12 '22 22:10

Pavlo