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
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 ...
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.
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.
You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With