关于javascript:基于另一个自定义数组对数组中的对象属性进行排序

Sort object properties in an array based on another custom array

本问题已经有最佳答案,请猛点这里访问。

我有一个对象数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"
            }];

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

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

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

iteam_order

预期结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"
            }];


您可以这样使用mapreduce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const item_array = [{"Email Address":"c","First Name":"a","Last Name":"b","Permission":"Training Administrator","Telephone":"d","User Group":"Company Administrator
<hr>
<p>
Using the reference array indices as the sorting order, implement the sort logic in the sort function and extract the keys of the object and sort them according to the given array and push the sorted object inside the original array.
</p>

<p>


[cc lang="
javascript"]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);