Remove Null from an Object and Sort object by key

York Chen
1 min readAug 26, 2020

有一物件中存有Null時,我們希望清除並重新排序

let Obj99 = {
qq99: null,
w995: 54,
qq98: 0,
qq497: 1,
c992: 168
}

利用!判斷是否為Null,如果是的話就刪除

接著Sort by Key

function Obj_remove_Null(obj) {
for (let null_element in obj) {
if (!obj[null_element])
//delete null
console.log("null_element", null_element)
{
delete (obj[null_element])
}
return (
(
//Sort JavaScript object by key
Object.keys(obj).sort().reduce((r, k) => (r[k] = obj[k], r), {})
)
)
}
}
console.log("Obj_remove_Null",Obj_remove_Null(Obj99));

--

--

York Chen

Cooking is an indispensable part of life. It is a taste that can’t be forgotten.