简体   繁体   中英

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'},
]

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 }));
<script>
    var arrayOfSquads=['Alfa','Betta','Gamma','Delta'];
    var arrayOfThingsThatHaveSquads=new Array();
    for(i=0;i<arrayOfSquads.length;i++)
    {
        arrayOfThingsThatHaveSquads.push({"squad":arrayOfSquads[i]});
    }
    console.log("What's lodash?");
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM