我有一个要显示的字段顺序列表
field_order = ["name", "age", "birthday"]
我有一个这样的对象列表
_data_set = {
"age": 23,
"birthday": "2000-12-12"
"name": "A"
}
我需要根据field_order
订购对象键。
预期结果:
_data_set = {
"name": "A",
"age": 23,
"birthday": "2000-12-12"
}
答案 0 :(得分:2)
自ES2015开始,JavaScript中的键顺序是按时间顺序排列的,因此我们可以这样进行排序:
有一篇不错的文章:property-traversal-order-es6
field_order = ["name", "age", "birthday"]
_data_set = {
"age": 23,
"birthday": "2000-12-12",
"name": "A"
};
let result = field_order.reduce( (obj, v) => {
obj[v] = _data_set[v];
return obj;
}, {});
console.log(result);
答案 1 :(得分:1)
首先,您需要排序,然后只创建具有所需键顺序的对象:
let field_order = ["name", "age", "birthday"];
let _data_set = {
"age": 23,
"birthday": "2000-12-12",
"name": "A"
}
let order = {name: -1, age: 0, birthday: 1};
const result = {};
Object.keys(_data_set)
.sort((a,b)=> order[a] - order[b])
.forEach(key=> result[key] = _data_set[key]);
console.log(result);
答案 2 :(得分:1)
您可以使用以下内容:
let new_data_set = {};
for(let item of field_order) {
new_data_set[item] = _data_set[item];
}