根据另一个自定义数组对数组中的对象属性进行排序

时间:2019-01-17 06:10:02

标签: javascript jquery arrays

我有一个对象数组

item_array = [{
                "Email Address": "c",
                "First Name": "a",
                "Last Name": "b",
                "Permission": "Training Administrator",
                "Telephone": "d",
                "User Group": "Company Administrator"
            },
            {
                "Email Address": "3",
                "First Name": "1",
                "Last Name": "2",
                "Permission": "6",
                "Telephone": "4",
                "User Group": "5"
            }];

如何按这样的给定数组对该数组进行排序

item_order = ["First Name", "Last Name", "Email Address", "Permission", "Telephone", "User Group"];

我需要像给定数组那样对对象的对象数组进行排序

  

iteam_order

预期结果

item_array = [{
                "First Name": "a",
                "Last Name": "b",
                "Email Address": "c",
                "Permission": "Training Administrator",
                "Telephone": "d",
                "User Group": "Company Administrator"
            },
            {
                "First Name": "1",
                "Last Name": "2",
                "Email Address": "3",
                "Permission": "6",
                "Telephone": "4",
                "User Group": "5"
            }];

2 个答案:

答案 0 :(得分:6)

您可以像这样使用mapreduce

const item_array = [{"Email Address":"c","First Name":"a","Last Name":"b","Permission":"Training Administrator","Telephone":"d","User Group":"Company Administrator"},{"Email Address":"3","First Name":"1","Last Name":"2","Permission":"6","Telephone":"4","User Group":"5"}],
      item_order = ["First Name","Last Name","Email Address","Permission","Telephone","User Group"];

const ordered = item_array.map(item =>
    item_order.reduce((acc, key) => ( acc[key] = item[key], acc ), {})
);

console.log(ordered)

答案 1 :(得分:1)

使用参考数组索引作为排序顺序,在sort函数中实现排序逻辑,提取对象的键,然后根据给定的数组对它们进行排序,然后将排序后的对象推入原始数组中。

var item_array = [{ "Email Address": "c", "First Name": "a", "Last Name": "b", "Permission": "Training Administrator",  "Telephone": "d", "User Group": "Company Administrator" }, {"Email Address": "3", "First Name": "1", "Last Name": "2", "Permission": "6", "Telephone": "4", "User Group": "5"}];
var item_order = ["First Name", "Last Name", "Email Address", "Permission", "Telephone", "User Group"];
item_array.forEach((obj, idx, arr) => {
           arr[idx] = Object.keys(obj)
                            .sort((a, b) => {
                             return item_order.indexOf(a) - item_order.indexOf(b);
                             })
                            .reduce((acc, ele)=>{acc[ele] = obj[ele]; return acc;},{});
                  });

console.log(item_array);