假设我有一个数组:
var users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
];
我想创建一个新数组:
var users = [
{person: {item : { user: 'barney', age: 36, active: true }}},
{person: {item : { user: 'fred', age: 40, active: false }}},
{person: {item : { user: 'travis', age: 37, active: true}}}
];
显然,解决方法是使用for循环来创建新数组,但我正在使用lodash在我的项目中操作我的数组.
只是想知道是否有任何lodash解决方案.
解决方法:
您可以将Array#map
用于新结构.
var users = [{ user: 'barney', age: 36, active: true }, { user: 'fred', age: 40, active: false }, { user: 'travis', age: 37, active: true}],
result = users.map(item => ({ person: { item } }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }