Javascript - maintain key order when going from object -> array

后端 未结 3 694
时光说笑
时光说笑 2021-01-14 08:08

I know key order isn\'t guaranteed in JS objects, however, my data structure comes from a backend for which I have no control over. Is there anything I can do to preserve th

3条回答
  •  旧时难觅i
    2021-01-14 08:28

    ECMA-262 does not specify enumeration order. The de facto standard is to match insertion order.

    No guarantees are given though on the enumeration order for array indices (i.e., a property name that can be parsed as an integer), because insertion order for array indices would incur significant memory overhead.

    EDIT: added jsfiddle example.

    var obj1 = {
       a: 'test1',
       b: 'test2' 
    };
    
    var obj2 = {
       2: 'test1',
       1: 'test2' 
    };
    // max 32bit unsigned is 2,147,483,647
    var obj3 = {
       2147483649: 'test1',
       2147483648: 'test2' 
    };
    // max 64bit unsigned is 9,223,372,036,854,775,807
    var obj4 = {
       9223372036854770: 'test1',
       9223372036854768: 'test2',
    };
    
    // != number < 2,147,483,647, order is not changed
    console.log(Object.keys(obj1));
    // < 2,147,483,647, order is changed
    console.log(Object.keys(obj2));
    // > 2,147,483,647, order is not changed in Firefox, but changed in Chrome
    console.log(Object.keys(obj3));
    // > 9,223,372,036,854,775,807, order is not changed in neither Firefox or Chrome
    console.log(Object.keys(obj4));
    

    Which means Chrome's javascript engine V8 will order any 64bit unsigned numbers, while Firefox's javascript engine SpiderMonkey will order any 32bit unsigned numbers.

提交回复
热议问题