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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

to add to this, i think i read somewhere that browsers handle differently ordering for object properties
what is a map object that is mentioned in the link? can I use it over here
do you have a link that explains array of objects with id?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.