Show original order of object properties in console.log

被刻印的时光 ゝ 提交于 2019-11-27 16:07:16
georg

console.log does indeed sort the properties, in some cases you can use JSON.stringify which preserves the order, e.g.

console.log(JSON.stringify(obj, null /*replacer function */, 4 /* space */))

NB: contrary to the popular belief, js objects maintain the enumeration order, as per the OwnPropertyKeys specification (integers first, then other properties in insertion order)

If you need to log a very big object, to be able to collapse keys, another option would be to transform it to key-value pair arrays.

let keepKeyOrder = function(obj) {
    if (typeof obj === 'object' && !Array.isArray(obj)) {
        let transformKey = (k) => [k, keepKeyOrder(obj[k])];
        return Object.keys(obj).map(transformKey);
    } else {
        return obj;
    }
};

console.log(keepKeyOrder({a:3,c:4,b:{b3:123,b2:234,b1:345}}));

Outputs:

Another easy solution would be:

console.log(Object.entries(obj).map(k=>({[k[0]]:k[1]})))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!