0

I read somewhere that order of keys in javascript objects is not guaranteed. Like browsers can decide to return whatever they feel like.

And that there is a new type of object in js called Map that allows you to have ordered objects.

But how do I use that when I send data from the server to the browser? There is no way to pass objects, I have to stringify with json and then the Map class becomes lost in the browser

Alex
  • 66,732
  • 177
  • 439
  • 641
  • what is exactly your question? I mean, you want to send a `Map` from the server to the client? or you want to specify an order for the properties of an object returning from the server? or what? – quirimmo Jan 12 '19 at 20:38
  • My question is how to get keys and values in the same order that were created on the server – Alex Jan 12 '19 at 20:39
  • 2
    JSON order is preserved. keys order of javascript objects is not. That's different. You do send back JSON from the server to the client, not javascript objects. – quirimmo Jan 12 '19 at 20:40
  • please see https://stackoverflow.com/questions/45957670/string-to-map-object-in-javascript – Tomás Jan 12 '19 at 20:44
  • Is the actual problem really the exact order of key-value pairs and not the index correspondence between Object.keys and Object.values? – Tommi Tuura Jan 12 '19 at 20:53
  • Are you trying to send an ordered `Map` from the server to the client, and make sure that the order is preserved? – Barmar Jan 12 '19 at 22:07
  • @quirimmo Once you do `JSON.parse` to get an object that you could enumerate, you will have a js object though. – Bergi Jan 13 '19 at 10:06
  • Notice that `Map` is not meant for ordered objects. Yes, it does have a guaranteed consistent iteration order, but it still represents an unordered collection. You cannot sort it. – Bergi Jan 13 '19 at 10:08
  • Why not simply send an array of key-value pairs? – Bergi Jan 13 '19 at 10:08
  • @Bergi right, but usually the issue with ordering is about how you iterate over them – quirimmo Jan 13 '19 at 10:08

1 Answers1

2

If you're trying to send an ordered map via JSON, and preserve the order, you can split the map into arrays of keys and values, then put them back together in the receiver.

Server:

function mapToJSON(map) {
    return JSON.stringify({keys: Array.from(map.keys()), values: Array.from(map.values())});
}

Client:

function JSONToMap(json) {
    const {keys, values} = JSON.parse(json);
    const map = new Map;
    keys.forEach(key, i) {
        map.set(key, values[i]);
    }
    return map;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612