David Chao

所有文章

Javascript object 如何保有原本的 key ordering

什麼時候 Javascript 的 Object 會有順序問題?

答案:Integer key 值會由小排到大,並且排序會大於其他 string key。

我們先寫一個 function log object 的順序。

javascript
function logObjectOrdering(targetObject) {
    Object.keys(targetObject).forEach(key => {
        console.log(key + ': ' + targetObject[key]);
    });
}

1. 一個正常的 object。

javascript
    let objectTest1 = {
        c: 'first',
        b: 'second',
        a: 'third',
    };

this.logObjectOrdering(objectTest1);

---Output---
c: first
b: second
a: third

沒問題,結果是我們要的。

2. 一個 key 由英文、數字混合而成的 object。

javascript
let objectTest2 = {
    c: 'first',
    5: 'second',
    b: 'third',
    3: '4th',
    a: '5th',
};

this.logObjectOrdering(objectTest2)

---Output---
3: 4th
5: second
c: first
b: third
a: 5th

沒問題,如果你剛好需要 Integer key 自動排序並永遠在前,那太感謝 javascript 了。

解決辦法

沒有解決辦法。

或許你可以查一下有沒有原生 function 能取得原本的順序,如果你打算這麼做的話,我幫你查好了。

javascript
console.log(Object.getOwnPropertyNames(objectTest2));
console.log(Reflect.ownKeys(objectTest2));

你可以試一下,我這邊不暴雷。

替代方案

1. 改用 map ,不是 array function 的 map,而是 ES6 新加入的資料型態,他可以保持原本的順序。

javascript
let mapTest1 = new Map([
    ['c', 'first'],
    [5, 'second'],
    ['b', 'third'],
    [3, '4th'],
    ['a', '5th'],
]);

mapTest1.forEach((value, key) => {
    console.log(key + ': ' + value);
});

2. 如果你有特殊原因非得用 Object,你只能把順序另外存在 array 當中了。

javascript
let objectTest3 = {
c: 'first',
5: 'second',
b: 'third',
3: '4th',
a: '5th',
};

let testOrder = ['c', 5, 'b', 3, 'a'];
testOrder.forEach(key => {
  console.log(key + ': ' + objectTest2[key]);
});