[英]how can I generate a new array by concatenate nested array objects by using lodash
I have an array of objects, and each objects may contain another array of objects, I want to concatenate values of nested array and generate a new array.我有一个对象数组,每个对象可能包含另一个对象数组,我想连接嵌套数组的值并生成一个新数组。
For example例如
lessons = [
{
id: 1,
description: string,
material: [{obj1}, {obj2}]
},
{
id: 2,
description: string,
material: [{obj3}]
},
{
id: 3,
description: string,
material: [{obj4}, {obj5}, {obj6}]
}
]
I want to generate a new array only contains material, expected output would like this我想生成一个只包含材料的新数组,预计 output 会这样
materials = [
{obj1},
{obj2},
{obj3},
{obj4},
{obj5},
{obj6}
]
how can I do that by using lodash?我怎样才能通过使用 lodash 做到这一点?
You can use .flatMap
to iterate over lessons
, and return all the material
lists in one array:您可以使用
.flatMap
迭代lessons
,并在一个数组中返回所有material
列表:
const lessons = [ { id: 1, description: 'string', material: [{obj1:1}, {obj2:2}] }, { id: 2, description: 'string', material: [{obj3:3}] }, { id: 3, description: 'string', material: [{obj4:4}, {obj5:5}, {obj6:6}] } ]; const res = _.flatMap(lessons, ({ material = [] }) => material); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.