0

I am making multiple objects, then I am JSON.stringifying them. Then I am turning them into a hash. I need all of the properties to be stringified in the same order so my hashes are consistent. For example:

function createObj(index, value, key) {
    var obj = {
        value: value,
        index: index,
        key: key
    };

    return obj;
 };


console.log(JSON.stringify(createObj(1, 'blue', 'ABC')));   // =>  {"value":"blue","index":1,"key":"ABC"}
console.log(JSON.stringify(createObj(2, 'red', 'DEF')));    // =>  {"value":"red","index":2,"key":"DEF"}
console.log(JSON.stringify(createObj(3, 'green', 'GHI')));  // =>  {"value":"green","index":3,"key":"GHI"}

Can I always expect the keys to be stringified in the order that I have placed them on the object in my createObj function? I do not add any more properties to the objects after they are created.

If I cannot guarantee this order, can you recommend a way to guarantee the order of the keys for this purpose?

EDIT: I realize that when iterating an object the order of the keys is not guaranteed (for-in and Object.keys) but would the order be guaranteed for stringifying it?

georgej
  • 2,401
  • 4
  • 17
  • 43
  • Possible duplicate of [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Dan Mandel Dec 04 '17 at 19:32
  • Just push it to the array. – Nikola Lukic Dec 04 '17 at 19:33
  • @NikolaLukic push it to what array? – georgej Dec 04 '17 at 19:42
  • The modern JavaScript standard provides more assurances about the behavior of property order than it used to, but to me it still seems really fragile to rely on it. However I understand (maybe) that it would be nice if stringifying an object that "looks" exactly like another object would give you exactly the same JSON serialization string. – Pointy Dec 04 '17 at 19:46
  • For what purpose do you need to guarantee the order? I would imagine for unit testing you can use `JSON.parse()` to check the validity of the returned object. – Xeraqu Dec 04 '17 at 19:49
  • @Xeraqu I am turning the `stringified` object into a hash so I want to keep the key order consistent in the string – georgej Dec 04 '17 at 19:50

1 Answers1

0

The JSON.stringify() documentation at MDN and the ECMAScript Language Specification do not indicate the order in which keys are stringified. While that order my very well be sequential for primitive types like string, number, and boolean, you can't really be sure for objects, functions, arrays, etc. Your best bet would likely be to implement your own version of stringify in order to be 100% certain of the output.

Xeraqu
  • 185
  • 2
  • 13