Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过使用lodash连接嵌套数组对象来生成新数组_Javascript_Arrays_Ecmascript 6_Lodash - Fatal编程技术网

Javascript 如何通过使用lodash连接嵌套数组对象来生成新数组

Javascript 如何通过使用lodash连接嵌套数组对象来生成新数组,javascript,arrays,ecmascript-6,lodash,Javascript,Arrays,Ecmascript 6,Lodash,我有一个对象数组,每个对象可能包含另一个对象数组,我想连接嵌套数组的值并生成一个新数组 比如说 lessons = [ { id: 1, description: string, material: [{obj1}, {obj2}] }, { id: 2, description: string, material: [{obj3}] }, { id: 3, description: string, material: [{obj4

我有一个对象数组,每个对象可能包含另一个对象数组,我想连接嵌套数组的值并生成一个新数组

比如说

lessons = [
 {
   id: 1,
   description: string,
   material: [{obj1}, {obj2}]
 },
 {
   id: 2,
   description: string,
   material: [{obj3}]
 },
 {
   id: 3,
   description: string,
   material: [{obj4}, {obj5}, {obj6}]
 }
]
我想生成一个只包含材质的新数组,预期输出如下

materials = [
   {obj1},
   {obj2},
   {obj3},
   {obj4},
   {obj5},
   {obj6}
 ]

如何使用lodash实现这一点?

您可以使用迭代
课程
,并在一个数组中返回所有
材料
列表:

const课程=[
{id:1,description:'string',材质:[{obj1:1},{obj2:2}]},
{id:2,description:'string',材质:[{obj3:3}]},
{id:3,description:'string',材质:[{obj4:4},{obj5:5},{obj6:6}]}
];
const res=u.flatMap(课程,({material=[]})=>material);
控制台日志(res)

我无法运行代码段,它显示未定义。我可以从lodash doc中看到它的用法,我可以这样写:const res=flatMap(lessons,e=>e.material | |[])而不加下划线吗?@RH st您说过您需要使用
lodash
,所以一定要安装它。如果您想正常使用它,请尝试以下操作:
lessons.flatMap(({material=[]})=>material)太棒了!那真的很有帮助!!非常感谢,我能要求更深入的解释吗?所以
lessons.flatMap()
意味着
lessons
已经成为第一个参数,它是集合,因此我们只需要传递第二个参数,即
({material=[]})=>material
作为iteratee函数,对吗?@RH st欢迎您。基本上,它是
数组中的一个函数。prototype
,参数是在每次迭代中执行的
回调
函数。这是文档的参考: