有没有一种方法可以给定引用数组来映射对象数组?

时间:2019-06-07 14:54:54

标签: javascript ecmascript-6

我目前正在尝试按照给定引用数组的相同顺序对对象数组进行排序。任何人都有基于性能的良好解决方案?这是下面的示例...

let example = () => {
    let referenceArray = ['name', 'date', 'creator','description'];

    let orderObject = [
        {type:'txt',orderBy:'date'},
        {type:'txt',orderBy:'name'},
        {type:'txt',orderBy:'description'},
        {type:'txt',orderBy:'creator'}
    ];

    // code to sort object here?

}

编辑:看来我能够实现一个解决方案。通过下面的代码,我能够将对象映射为与数组相同的顺序。

let example = () => {
    let referenceArray = ['name', 'date', 'creator','description'];
    let copy = [];
    let orderObject = [
        {type:'txt',orderBy:'date'},
        {type:'txt',orderBy:'name'},
        {type:'txt',orderBy:'description'},
        {type:'txt',orderBy:'creator'}
    ];

    // code to sort object here?
    orderObject.forEach((x) => {
        let index = referenceArray.indexOf(x.orderBy);
        copy.splice(index,0,x);
    });
}

1 个答案:

答案 0 :(得分:1)

看起来我能够实现自己的解决方案。

let example = () => {
    let referenceArray = ['name', 'date', 'creator','description'];
    let copy = [];
    let orderObject = [
        {type:'txt',orderBy:'date'},
        {type:'txt',orderBy:'name'},
        {type:'txt',orderBy:'description'},
        {type:'txt',orderBy:'creator'}
    ];

    // code to sort object here?
    orderObject.forEach((x) => {
        let index = referenceArray.indexOf(x.orderBy);
        copy.splice(index,0,x);
    });
}