开发者

Syntax for creating objects with composite keys in JavaScript

Is there a syntax for passing composite keys, i.e. lists and objects,

like the below example开发者_Python百科, or is that by-design?

> obj = {[1, 2]: 3};
SyntaxError: Unexpected token [

The second example works fine, it's not bad but I'd like to know if there is an alternative way.

> obj = {};
> obj[[1, 2]] = 3;
3
> [1, 2] in obj;
> true


Object property names in JavaScript are at the end just strings, your second example seems to work because the bracket property accessor converts the [1, 2] expression to String (returning "1,2"), for example:

var obj = {};
obj[[1, 2]] = 3;

console.log(obj["1,2"]); // 3

Another example:

var foo = { toString: function () { return "bar"; } },
    obj = {};

obj[foo] = 3; // foo is converted to String ("bar")
console.log(obj["bar"]); // 3

See also:

  • jshashtable


If you don't want to do string concatenation you can use nested maps, then a wrapper to make the code a less verbose. Here's an example in TypeScript.

class MapMap<Ka, Kb, V> implements Iterable<[Ka, Kb, V]> {
  readonly mm = new Map<Ka, Map<Kb, V>>()

  get(a: Ka, b: Kb): V | undefined {
    const m = this.mm.get(a)
    if (m !== undefined) {
      return m.get(b)
    }
    return undefined
  }

  set(a: Ka, b: Kb, v: V): void {
    let m = this.mm.get(a)
    if (m === undefined) {
      this.mm.set(a, (m = new Map()))
    }
    m.set(b, v)
  }

  *[Symbol.iterator](): Iterator<[Ka, Kb, V]> {
    for (const [a, m] of this.mm) {
      for (const [b, v] of m) {
        yield [a, b, v]
      }
    }
  }
}


do you need the [1, 2] to be preserved as an array? what would this exactly enable you to do? I'm not familiar with "composite keys" so maybe a short explanation for link to one to clarify would help me understand your problem better.

if you just want to use [1, 2] as a key, you can always use that as a string:

var obj = {  
  "[1, 2]": 3
}

but again, i would assume you would want to keep [1, 2] as an array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜