order by object property javascript code example
Example 1: sort by object property javascript
let list = [
{
name: "world"
},
{
name: "hello",
},
];
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));
console.log(x);
Example 2: hange the order of properties in object javascript
function preferredOrder(obj, order) {
const newObj: any = {};
for (let key of order) {
newObj[key] = obj[key];
}
return newObj;
}
preferredOrder(obj: any, keyOrder: any[]) {
keyOrder.forEach((k) => {
const v = obj[k]
delete obj[k]
obj[k] = v
})
}