我有这样的对象数组:
[ { season: 1,
episodes:
[
{
title:'ep1 title',
season:1,
},
{
title:'ep2 title',
season:1,
},
{
title:'ep3 title',
season:1,
}] },
{ season: 2,
episodes:
[ {
title:'ep1 title',
season:2,
},
{
title:'ep2 title',
season:2,
},
{
title:'ep3 title',
season:2,
} ] },
{ season: 3,
episodes:
[ {
title:'ep1 title',
season:3,
},
{
title:'ep2 title',
season:3,
},
{
title:'ep3 title',
season:3,
} ] },
]
我想用loadsh将它变成这样的数组:
[
{
title:'ep1 title',
season:1,
},
{
title:'ep2 title',
season:1,
},
{
title:'ep3 title',
season:1,
},
{
title:'ep1 title',
season:2,
},
{
title:'ep2 title',
season:2,
},
{
title:'ep3 title',
season:2,
},
{
title:'ep1 title',
season:3,
},
{
title:'ep2 title',
season:3,
},
{
title:'ep3 title',
season:3,
}
]
我只是想收看剧集 使用lodash将对象转换为数组 如何使用lodash将两个数组合并到一个对象中 lodash:从对象数组中计算值
答案 0 :(得分:5)
您可以在data
上使用纯JavaScript:
var flat = [].concat(...data.map( o => o.episodes ));
var data = [ { season: 1,
episodes:
[
{
title:'ep1 title',
season:1,
},
{
title:'ep2 title',
season:1,
},
{
title:'ep3 title',
season:1,
}] },
{ season: 2,
episodes:
[ {
title:'ep1 title',
season:2,
},
{
title:'ep2 title',
season:2,
},
{
title:'ep3 title',
season:2,
} ] },
{ season: 3,
episodes:
[ {
title:'ep1 title',
season:3,
},
{
title:'ep2 title',
season:3,
},
{
title:'ep3 title',
season:3,
} ] },
];
var flat = [].concat(...data.map( o => o.episodes ));
console.log(flat);

.as-console-wrapper { max-height: 100% !important; top: 0; }

如果真的必须是lodash,你可以使用_.flatMap
:
var flat = _.flatMap(data, 'episodes');
var data = [ { season: 1,
episodes:
[
{
title:'ep1 title',
season:1,
},
{
title:'ep2 title',
season:1,
},
{
title:'ep3 title',
season:1,
}] },
{ season: 2,
episodes:
[ {
title:'ep1 title',
season:2,
},
{
title:'ep2 title',
season:2,
},
{
title:'ep3 title',
season:2,
} ] },
{ season: 3,
episodes:
[ {
title:'ep1 title',
season:3,
},
{
title:'ep2 title',
season:3,
},
{
title:'ep3 title',
season:3,
} ] },
];
var flat = _.flatMap(data, 'episodes');
console.log(flat);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
答案 1 :(得分:0)
无需使用任何特殊的lodash函数 - 这可以通过基本的javascript数组.reduce()
非常容易地完成,如下所示:
var oldArr = [{
season: 1,
episodes: [{
title: 'ep1 title',
season: 1,
},
{
title: 'ep2 title',
season: 1,
},
{
title: 'ep3 title',
season: 1,
}
]
},
{
season: 2,
episodes: [{
title: 'ep1 title',
season: 2,
},
{
title: 'ep2 title',
season: 2,
},
{
title: 'ep3 title',
season: 2,
}
]
},
{
season: 3,
episodes: [{
title: 'ep1 title',
season: 3,
},
{
title: 'ep2 title',
season: 3,
},
{
title: 'ep3 title',
season: 3,
}
]
},
]
var newArr = oldArr.reduce(function(result, current) {
return result.concat(current.episodes);
}, []);
console.log(newArr);