How to iterate javascript object properties in the order they were written

前端 未结 4 1650
抹茶落季
抹茶落季 2020-11-29 12:00

I identified a bug in my code which I hope to solve with minimal refactoring effort. This bug occurs in Chrome and Opera browsers. Problem:

var obj = {23:\"A         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 12:46

    @bobince is right, Objects don't keep any ordering metadata.

    In my case it didn't make sense to refactor to an array, so I submit another solution: create an array with your ordering and use it to map your object properties in order:

    const obj = {
        'r': '#f00',
        'g': '#0f0',
        'b': '#00f',
    };
    const objMap = ['b','r','g'];
    
    objMap.map((key, index) => {
        console.log(`array index: ${index}`);
        console.log(`object index: ${key}`);
        console.log(`object property: ${obj[key]}\n`);
    });
    

    Output:

    array index: 0
    object index: b
    object property: #00f
    
    array index: 1
    object index: r
    object property: #f00
    
    array index: 2
    object index: g
    object property: #0f0
    

提交回复
热议问题