I am making multiple objects, then I am JSON.stringify
ing 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 stringify
ing it?