如何在包含 objects 嵌套数组的 objects 数组中使用 _sortBy

How to use _sortBy in an array of objects that contains nested array of objects

我有一个 objects 的数组列表,其中包含一个 objects 的嵌套数组,如下所示:

const mainList = [
{
    id:'001',
    category: 'A',
    content: [ 
        {
            title: 'Apples',
            language: 'en'
        },
        {
            title: '苹果',
            language: 'zh-cn'
        },
        {
            title: '苹果HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'002',
    category: 'B',
    content: [
        {
            title: 'Grapes',
            language: 'en'
        },
        {
            title: '葡萄',
            language: 'zh-cn'
        },
        {
            title: '葡萄HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'003',
    category: 'C',
    content: [
        {
            title: 'Bananas',
            language: 'en'
        },
        {
            title: '香蕉',
            language: 'zh-cn'
        },
        {
            title: '香蕉HK',
            language: 'zh-hk'
        },
    ]
}
]

我想使用 lodash _sortBy 显示此列表,按其标题按字母顺序排列,如下所示:

Apples, Bananas, Grapes

我的做法:

console.log(_sortBy(mainList.content.title))

但是结果返回undefined at index 0

提前致谢!

您使用sortBy的方式不正确,您可以这样使用sortBy:

console.log(_.sortBy(mainList, "content.title"));

但列表中没有content.title,所以你需要指定要排序的内容索引content[0].title

所以按标题排序的正确方法是这样的:

console.log(_.sortBy(mainList, "content[0].title"));

您真的不需要 lodash 来进行排序:

const list = [{id:'001', category: 'A', 
                   content: [{title: 'Apples',language: 'en'},
                             {title: '苹果',language: 'zh-cn'},
                             {title: '苹果HK', language: 'zh-hk'}]},
                  {id:'002', category: 'B',
                   content: [{title: 'Grapes',language: 'en'},
                             {title: '葡萄',language: 'zh-cn'},
                             {title: '葡萄HK',language: 'zh-hk'}]},
                  {id:'003', category: 'C',
                   content: [{title: 'Bananas',language: 'en'},
                             {title: '香蕉',language: 'zh-cn'},
                             {title: '香蕉HK',language: 'zh-hk'}]}
                 ];

const srtv=o=>o.content[0].title;
console.log(list.sort((a,b)=>srtv(a).localeCompare(srtv(b))))