0

Quick question guys, I am combining two objects using spread syntax, the new object is sorted automatically by keys of previous two objects, I dont want my new object to be sorted by keys (because I want users to see older conversations in my redux state above and newly fetched conversations). What can I do?

Here is my reducer, that takes array of conversations (array has 3 conversations first time around, and then +1 with another hit), and create objects based on conversation id

case actions.SET_CONVERSATION_MESSAGES: {
let convos = {};
payload.chatinbox.forEach(message => {
  if (state[ message.chatsession_id ]) {
    convos = Object.assign(convos, {
      [ message.chatsession_id ]: {
        messages: [...state[ message.chatsession_id ].messages, message]
      }
    });
  } else if (!state[ message.chatsession_id ]) {
    convos = Object.assign(convos, {
      [ message.chatsession_id ]: {
        messages: [message]
      }
    });
  }
});
return {
  ...convos,
  ...state
   };
}

here is how state object look

{
 14632: {},
 14652: {},
 14741: {}
}

and when a new conversation comes in that has a key that fits in between

{
  14542: {}
}

the new object get automatically sorted by them

{
 14632: {},
 14542: {},
 14652: {},
 14741: {}
}

and the result that I want is

{
 14632: {},
 14652: {},
 14741: {},
 14542: {}
} 

for obvious reason, to show user what is fetched before and what is fetched afterwards, what can I do?

xtabbas
  • 567
  • 2
  • 8
  • 18

1 Answers1

4

Objects don't guarantee order, so the keys can be shuffled around depending on browser implementation. If you want order to be maintained, consider using an array of objects with ids instead.

If you're using the IDs for direct access to the object, you might find array.find helpful if you transition to using an array of objects with IDs.

Community
  • 1
  • 1
Joseph
  • 107,072
  • 27
  • 170
  • 214
  • to add to this, i think i read somewhere that browsers handle differently ordering for object properties – Kaddath Mar 01 '17 at 14:49
  • what is a map object that is mentioned in the link? can I use it over here – xtabbas Mar 01 '17 at 15:13
  • do you have a link that explains array of objects with id? – xtabbas Mar 01 '17 at 15:16
  • This is what I am reading.. Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. – xtabbas Mar 01 '17 at 15:24