I have looked at this question in stack overflow about objects guaranteeing order. Does JavaScript Guarantee Object Property Order?
some says they guarantee, some says they don't, depending on situations. Meantime I've encountered following problem.
I have an array of objects, similar to below:
const arrayObject = [
{id:'a123', bar:'hello'},
{id:'a321', bar: 'foo'} ];
now I wish to turn this arrayObject into object of object, with structure as follows with the same order as the array:
const object = {
'a123': {id:'a123', bar:'hello'},
'a321': {id:'a321', bar: 'foo'},
}
basically using the id of each item in the array as the key of the object. Below is the code I used to try to achieve it:
let newObj = {};
arrayObject.forEach(data=>{
const temp = {
[data.id]:{
id: data.id,
bar: data.bar
},
};
newObj={...newObj, ...temp};
})
I do get the correct structure, however the order is not the same as the order of arrayObject, i.e. it returns:
const object = {
'a321': {id:'a321', bar: 'foo'},
'a123': {id:'a123', bar:'hello'},
}
I've tried with more items in the array, and I get same result. It does not guarantee the order.
Is there something wrong with my code, or is it simply not guaranteeing the order?
What do I have to do to make the object be the same order as the array?