Javascript sort object key indexes

here is my structure/example:

let arrWeekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];

let obj1 = {
 'Montag' : ['test string'],
 'Dienstag' : ['test string'],
 'Mittwoch' : ['test string'],
 'Donnerstag' : ['test string'],
 'Freitag' : ['test string'],
 'Samstag' : ['test string']
}

let obj2 = {
 'Donnerstag' : ['test string'],
 'Samstag' : ['test string'],
 'Montag' : ['test string'],
 'Dienstag' : ['test string'],
 'Mittwoch' : ['test string'],
 'Freitag' : ['test string']
}


for ( key in objWeekdays ) {
  // do something
}

"objectWeekdays" in for in loop is sometimes ordered object as "obj1", but sometimes also unordered as "obj2".

My problem:

for in with obj1 => key index of "Montag" is 0

for in with obj2 => key index of "Montag" is 2

Is there any way to sort Object keys before "for in" loop?

I would like always to start with "Montag" in for in loop.

Thanks in advance for any advice or help.javascri

6 thoughts on “Javascript sort object key indexes”

  1. We could get the entries for obj2 using Object.entries, sort them, then use Object.fromEntries to re-create it.

    One has be very careful in general about depending on property order. This depends on property creation order. If you wish to iterate properties this way it’s probably best to get an array of keys / entries, sort them, then iterate.

    let obj2 = {
     'Donnerstag' : ['test string'],
     'Samstag' : ['test string'],
     'Montag' : ['test string'],
     'Dienstag' : ['test string'],
     'Mittwoch' : ['test string'],
     'Freitag' : ['test string']
    }
    
    let entries = Object.entries(obj2);
    entries.sort(([key1, v1], [key2, v2]) => key1.localeCompare(key2));
    let obj2Sorted = Object.fromEntries(entries);
    console.log("Obj2, sorted:", obj2Sorted);
    Reply
  2. Short answer: There is no way you can "sort" them becausere there simply is no need to do so.

    Anyways if you really want to place those attributes in a specific order you would have to create a new object with the desired order. Remember this order is not permanent and is most likely to change.

    The ordering of object properties is non-standard in ECMAScript. You should never make assumptions about the order of elements in a JavaScript object. An Object is an unordered collection of properties. The answers below show you how to "use" sorted properties, using the help of arrays, but never actually alter the order of properties of objects themselves. So, no, it’s not possible. Even if you build an object with presorted properties, it is not guaranteed that they will display in the same order in the future.

    As stated in Sorting object property by values.

    Reply
  3. Even if the properties are inserted in the right order, you still cannot (or should not) rely on it. However you can definitely implement your own iterator, here’s a contrived example:

    // object of days; not in "human" order
    const days = {
      wed: 3,
      sat: 6,
      mon: 1,
      sun: 7,
      fri: 5,
      tue: 2,
      thu: 4
    };
    
    days[Symbol.iterator] = function* () {
      yield this.mon;
      yield this.tue;
      yield this.wed;
      yield this.thu;
      yield this.fri;
      yield this.sat;
      yield this.sun;
    };
    
    
    for (d of days) {
      console.log('for..of', d);
    }
    
    console.log('...days', ...days);
    Reply
  4. You could iterate with the array of weekdays and check if the property exists for further processing.

    This approach takes the wanted order for all objects.

    function iterate(object, days) {
        for (const day of days) {
            if (!(day in object)) continue;
            console.log(object[day]);       // processing
        }
    }
    
    // call
    iterate(object1, arrWeekdays);
    
    Reply

Leave a Comment