使用动态嵌套属性键对数组中的对象进行排序 [英] Sort objects in array with dynamic nested property keys

查看:68
本文介绍了使用动态嵌套属性键对数组中的对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对嵌套对象的数组进行排序.它正在使用静态选择的键,但我不知道如何动态获取它.

I'm trying to sort an array of nested objects. It's working with a static chosen key but I can't figure out how to get it dynamically.

到目前为止,我已经有了这段代码

So far I've got this code

sortBy = (isReverse=false) => {
    this.setState(prevState => ({
        files: prevState.files.sort((a, b) => {
            const valueA = (((a || {})['general'] || {})['fileID']) || '';
            const valueB = (((b || {})['general'] || {})['fileID']) || '';

            if(isReverse) return valueB.localeCompare(valueA);

            return valueA.localeCompare(valueB);
        })
    }));
}

这时,键是硬编码的 ['general'] ['orderID'] ,但我希望通过向 sortBy 函数:

At this point the keys are hardcoded ['general']['orderID'] but I want this part to be dynamic by adding a keys param to the sortBy function:

sortBy = (keys, isReverse=false) => { ...

keys 是带有嵌套键的数组.对于上面的示例,它将是 ['general','fileID'] .

keys is an array with the nested keys. For the above example, it will be ['general', 'fileID'].

要使其动态化,需要采取哪些步骤?

What are the steps that need to be taken to make this dynamic?

注意:子对象可以是未定义的,因此我使用的是 a ||.{}

注2:我正在使用es6.没有外部软件包.

推荐答案

一种方法可能是使用

One way could be using reduce() over the new keys argument, something like this:

sortBy = (keys, isReverse=false) =>
{
    this.setState(prevState =>
    ({
        files: prevState.files.slice().sort((a, b) =>
        {
            const valueA = (keys.reduce((acc, key) => (acc || {})[key], a) || '').toString();
            const valueB = (keys.reduce((acc, key) => (acc || {})[key], b) || '').toString();
            return (isReverse ? valueB.localeCompare(valueA) : valueA.localeCompare(valueB));
        })
    }));
}

这篇关于使用动态嵌套属性键对数组中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆