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

Viewed 64

I have a list of array of objects that contains a nested array of objects like so:

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'
        },
    ]
}
]

I want to display this list using lodash _sortBy, by its title in alphabetical order like this:

Apples, Bananas, Grapes

My approach:

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

But the result comes back with undefined at index 0

Thanks in advance!

2 Answers

the way you used sortBy is incorrect, you can use sortBy like this:

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

but the list does not have content.title, So you need to specify the index of content you want to sort by content[0].title

so the correct way to sort by title is like this:

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

You ndon't really need lowdash to do the sorting:

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))))

Related