'Variable as the property name in a JavaScript object literal? [duplicate]
Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Use variable for property name in JavaScript literal?
Is it possible to add a variable as the property name of an object in JavaScript, like this:
var myVar = "name";
var myObject = {
{myVar}: "value"
};
Solution 1:[1]
Edit
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
var myVar = "name";
var myObject = {
[myVar]: "value"
};
You can use the [] syntax to use an expression as the property name (compared to the .prop and prop: value syntaxes where they are always treated as strings):
var myObject = {};
var myVar = "name";
myObject[myVar] = "value";
There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.
Solution 2:[2]
Like this?
var myVar = "name";
var myObject = {};
myObject[myVar] = "value";
Solution 3:[3]
Yes, but not directly.
var myVar = "name";
var object = {};
object[myVar] = "value";
Solution 4:[4]
Update: I have found a way to achieve the desired output with below steps.
- I use array_agg with distinct. I also make an additional column start which contains the minimum value in form of an array.The output at this point will look like below.
X A start
dummy [1,2,3,4,5] [1]
- At this point, I use reduce function of presto. I take the last element from the start and compare it with the current element of array. If the difference is <2 I update start by appending the last element of the array else I use the current element of the array and this is stored in b.
reduce(A, start, case when x - s[cardinality(s)] < 2 then s || s[cardinality(s)] else s || x end, s-> s) as b
The final output shall be like below.
X A start b
dummy [1,2,3,4,5] [1] [1,1,3,3,5]
- Next step is obvious, we simply explode b after using array_distinct and join with proper conditions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maciej Bledkowski |
| Solution 2 | Blender |
| Solution 3 | Niet the Dark Absol |
| Solution 4 | mw981 |
