0

I have an array containing some IDs:

let ids = [ '184', '085', '241', '086', '087', '165' ];

and an empty object - let data = {};

I am looping through the array and setting each of the elements as a property of the object:

ids.forEach(id => {
    data[id] = '';
});

I expect the data object to be:

{ '184': '', '085': '', '241': '', '086': '', '087': '', '165': '' }

But when I console.log(data) I find that the order of the properties is messed up and data is:

{ '165': '', '184': '', '241': '', '085': '', '086': '', '087': '' }

I have tried looping through the array with this method also:

for (let id of ids) {
    data[id] = '';
}

But the same messed-up order results. I need to know how can I set the properties in correct order and, more importantly, what is causing this issue.

Dev.Mehul
  • 96
  • 7
  • 3
    Objects aren't ordered data structures - you access their content by prop name, not index. If order matters, keep the array. – jonrsharpe Aug 12 '20 at 14:09
  • 2
    As jonrsharpe said - this wont be possible as object keys themselves are never ordered. May I ask you why you want them in an ordered fashion? Do you need to do anything with them in a certain order? – David Losert Aug 12 '20 at 14:10
  • 1
    @DavidLosert Actually, object keys do have a defined order. See https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – iota Aug 12 '20 at 14:13
  • @jonrdharpe I thought I had read somewhere that now object properties do have an order. That order is insertion based , i.e oldest inserted property coming before the recent insertions... – Dev.Mehul Aug 13 '20 at 03:18

1 Answers1

1

You need to use a Map instead to maintain insertion order. Object keys are ordered in insertion order, except for numeric keys which are ordered in ascending order.

let ids = [ '184', '085', '241', '086', '087', '165' ];
const map = new Map;
ids.forEach(id => map.set(id, ''));
map.forEach((val,key)=>console.log(key,'=',val));
iota
  • 34,586
  • 7
  • 32
  • 51