Eric Ahn
Eric Ahn

Reputation: 401

Javascript appending object doesn't guarantee order

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?

Upvotes: 1

Views: 448

Answers (3)

thingEvery
thingEvery

Reputation: 3434

I think what you're looking for is a Map() object. See here -> Map and Set

const arrayObject = [
  {id:'a123', bar:'hello'}, 
  {id:'a321', bar: 'foo'},
  {id:'a234', bar: 'more'},
  {id:'a735', bar: 'words'},
  {id:'a167', bar: 'added'},
  {id:'a857', bar: 'now'},
];

var newObj = new Map();

for (var i=0; i<arrayObject.length; i++) {
  const temp = {
        id: arrayObject[i].id,
        bar: arrayObject[i].bar
   };
   newObj.set(arrayObject[i].id, temp);
}

var jsonText = JSON.stringify(Array.from(newObj.entries()));

console.log(jsonText);

// To get at the elements, use .get()

console.log(newObj.get("a321").bar);

Upvotes: 1

danh
danh

Reputation: 62686

Preserve the order by including ordering information in the (unordered) object. Anytime later, when you need to recover the original order, use the saved ordering information...

const arrayObject = [{
    id: 'a123',
    bar: 'hello'
  },
  {
    id: 'a321',
    bar: 'foo'
  }
];

let object = {}
arrayObject.forEach((e, i) => {
  object[e.id] = { ...e, orderWith: i } // the index will tell us how to sort later
})

// later on
let sorted = Object.values(object).sort((a, b) => a.orderWith - b.orderWith)
console.log(sorted)

Upvotes: 3

Always Learning
Always Learning

Reputation: 5581

A simpler bit of code would be like this (use a for loop instead of forEach:

let newObj = {};
for (const data of arrayObject) {
  newObj[data.id] = data;
}

This might get you what you want because it will guarantee that the order the object is built matches the order in the array. Using forEach causes multiple functions to be called in whatever order they run, which might be out of order. But realize that even using the for-loop does not guarantee the order will always match. An Array will guarantee the order, but the Object made this way does not. Even if the above code does give you the desired order, it might not in the future. Use an Array if you need to preserve order.

Upvotes: 0

Related Questions