我如何使用lodash,用最少的代码转换像这样的数组:
['Alfa','Betta','Gamma','Delta']
成:
[
{ squad: 'Alfa'},
{ squad: 'Betta'},
{ squad: 'Gamma'},
{ squad: 'Delta'},
]
答案 0 :(得分:14)
在Lo-Dash(或Underscore)中:
_.map(['Alpha', 'Beta', 'Gamma', 'Delta'], function (squad) {
return { squad: squad };
});
在ES5中:
['Alpha', 'Beta', 'Gamma', 'Delta'].map(function (squad) {
return { squad: squad };
});
在ES2015中:
['Alpha', 'Beta', 'Gamma', 'Delta'].map(squad => ({ squad }));
答案 1 :(得分:-7)
<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>