使用 Javascript 对象作为对象键
我正在尝试设计一种方法来使用简单的 Javascript 对象(一级深键值对)作为另一个对象的键。我知道仅使用没有字符串化的对象将导致 [Object object]
被用作键;请参阅以下内容:在 JavaScript 中使用对象作为属性键(因此该问题不是重复的)。
有一篇关于它的博客文章考虑到了这一点,并且还考虑了按对象键排序的需要,因为它们的顺序无法保证,但包含的 Javascript 代码运行超过 100 行。我们正在使用 underscore.js 库,因为它与主干密切相关,但纯 Javascript 替代品也将引起人们的兴趣。
I am trying to devise a way to use a simple Javascript object (one level deep key value pairs) as a key to another object. I am aware that merely using the object without stringification will result in [Object object]
being used as the key; see the following: Using an object as a property key in JavaScript (so this question is not a duplicate).
There is a blog post about it that takes this into account and also accounts for the need to sort by object key since their order is not guaranteed, but the included Javascript code runs over a 100 lines. We are using the underscore.js library since that goes hand in hand with backbone but pure Javascript alternatives will also be of interest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我编写了一个接受任意键的哈希表实现,但我怀疑您会因为文件大小相对较大而拒绝它。
https://code.google.com/p/jshashtable/
I wrote a hash table implementation that accepts arbitrary keys but I suspect you'll reject it on the grounds of the relatively large file size.
https://code.google.com/p/jshashtable/
这是一个基于下划线的解决方案,它首先将对象转换为键值对。
Here is an underscore based solution that relies on first converting the object to key-value pairs.
你可以使用这样的模式。这样,对象的密钥就是为每个对象生成的随机 ID。
You could use a pattern like this. This way, your key for an object is this random id that you generate for every object.
在 ECMAScript 6 中,您将能够使用地图。
In ECMAScript 6 you'll be able to use Maps.