[英]Will these object keys always be in same order?
I am making multiple objects, then I am JSON.stringify
ing them. 我正在制作多个对象,然后将它们进行
JSON.stringify
。 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? 我是否总能期望将密钥放在
createObj
函数中的对象上的顺序进行字符串化处理? 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? 编辑:我意识到,迭代对象时,不能保证键的顺序(
for-in
和Object.keys
),但是可以保证将其stringify
的顺序吗?
The JSON.stringify()
documentation at MDN and the ECMAScript Language Specification do not indicate the order in which keys are stringified. MDN上的
JSON.stringify()
文档和ECMAScript语言规范没有指出密钥的字符串排序顺序。 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. 虽然该顺序对于诸如
string
, number
和boolean
类的原始类型来说是很好的顺序排列,但您不能真正确定对象,函数,数组等的顺序。最好的选择是按顺序实现自己的stringify
版本100%确定输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.