使用Javascript对象作为对象键 [英] Using Javascript object as object key

查看:69
本文介绍了使用Javascript对象作为对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设计一种使用简单Javascript对象(一级深键值对)作为另一个对象的键的方法.我知道,仅使用不带字符串化的对象将导致[Object object]被用作键;请参阅以下内容:在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).

关于它的博客文章考虑到了这一点,并且还考虑了按对象键排序的需求,因为不能保证它们的顺序,但是所包含的Javascript代码运行了100行.我们正在使用underscore.js库,因为它与主干网紧密相连,但纯Javascript替代方案也将引起人们的兴趣.

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.

推荐答案

在ECMAScript 6中,您将可以使用

In ECMAScript 6 you'll be able to use Maps.

var map = new Map();

var keyObj = { a: "b" },
    keyFunc = function(){},
    keyString = "foobar";

// setting the values
map.set(keyObj,    "value associated with keyObj");
map.set(keyFunc,   "value associated with keyFunc");
map.set(keyString, "value associated with 'foobar'");

console.log(map.size);              // 3

// getting the values
console.log(map.get(keyObj));       // "value associated with keyObj"
console.log(map.get(keyFunc));      // "value associated with keyFunc"
console.log(map.get(keyString));    // "value associated with 'a string'"

console.log(map.get({ a: "b" }));   // undefined, because keyObj !== { a: "b" }
console.log(map.get(function(){})); // undefined, because keyFunc !== function(){}
console.log(map.get("foobar"));     // "value associated with 'foobar'"
                                    // because keyString === 'foobar'

这篇关于使用Javascript对象作为对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆