有一个包含这样的对象的数组:
[{id: "58eeed338b115", name: "Bob", avatar: "" },
{id: "58eeed338b115", name: "Bob", avatar: "" }]
我需要更改属性的顺序:
[{avatar: "", name: "Bob",id: "58eeed338b115"},
{avatar: "", name: "Bob",id: "58eeed338b115"} ]
在实际任务中我有大约20个obj,如何改变秩序?用于?我不知道如何做到这一点。我想设置manualy命令,obj中的参数可以是大约10
答案 0 :(得分:0)
const arr = [{id: "58eeed338b115", name: "Bob", avatar: "" },
{id: "58eeed338b115", name: "Bob", avatar: "" }]
const sortOrder = {'avatar': 1, 'id': 2, 'name': 3}
const res = arr.map(o => Object.assign({}, ...Object.keys(o).sort((a, b) => sortOrder[a] - sortOrder[b]).map(x => { return { [x]: o[x]}})))
console.log(JSON.stringify(res, null, 2))
答案 1 :(得分:-1)
尝试:
const sortObj = ({id, name, avatar, ...more}) => ({avatar, name, id, ...more})
const objs = [...]
const objsSorted = objs.map(sortObj)
答案 2 :(得分:-1)
var sortObj = function sortObj(obj) {
let keys = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.sort();
let newObj = {};
for (let i = 0; i < keys.length; ++i) {
newObj[keys[i]] = obj[keys[i]];
}
return newObj;
};
let arr = [{id: "58eeed338b115", name: "Bob", avatar: "" },
{id: "58eeed338b115", name: "Bob", avatar: "" }];
for (let i = 0; i < arr.length; ++i) {
console.log(sortObj(arr[i]));
}