Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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
like image 454
Nick Dandoulakis Avatar asked Jun 16 '11 18:06

Nick Dandoulakis


People also ask

How do you create a composite key?

A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made ...

How I make a an object key in JavaScript?

The Object keys can be attained using the Object. keys() method. In JavaScript, the Object. keys() method returns an array containing all the object's own enumerable property names.

What is a composite key example?

In a table representing students our primary key would now be firstName + lastName. Because students can have the same firstNames or the same lastNames these attributes are not simple keys. The primary key firstName + lastName for students is a composite key.

How do you create a key for an object?

You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.


1 Answers

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
like image 121
Christian C. Salvadó Avatar answered Sep 22 '22 02:09

Christian C. Salvadó