Reputation: 647
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?
Upvotes: 0
Views: 244
Reputation: 119837
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.
Upvotes: 4