使用 lodash 是将数据从数组映射到单个数组的好方法

Using lodash what is a good way of mapping data from arrays into a single array?

本文关键字:数组 单个 方法 映射 使用 数据 lodash      更新时间:2023-09-26

使用 lodash 将下面的数据映射到单个 level2 对象数组的快速方法是什么?

    SomeObject = {
    name: 'someObject',
    level1: [
        {
            id: '1',
            level2: [
                { someValue: 'example1'},
                { someValue: 'example2'},
                { someValue: 'example3'},
                { someValue: 'example4'}
            ]
        },
        {
            id: '2',
            level2: [
                { someValue: 'example5' },
                { someValue: 'example6' },
                { someValue: 'example7' },
                { someValue: 'example8' }
            ]
        },
        {
            id: 'n',
            level2: [
                { someValue: 'examplen' },
            ]
        }
    ]
}

输出:

[
 'example1',
 'example2',
 'example3',
 'example4',
 'example5',
 'example6',
 'example7',
 'example8',
 'examplen',
]

忽视:Stackflow比我聪明,所以我必须输入更多的非代码内容才能停止抱怨。所以我会输入更多,以便我可以发布。

您可以使用

flatMap()将所有"level2"数组收集到单个数组中,然后使用简单的map()提取"someValue"属性

_.map(_.flatMap(SomeObject.level1, "level2"),"someValue")