javascript use variable as key code example

Example 1: variable key name js

//You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

Example 2: javascript create object key from variable

//For ES6 and Babel
{
    [yourKeyVariable]: "yourValue",
}

// ES5 Alternative
// Create the object first, then use [] to set your variable as a key
var yourObject = {};

yourObject[yourKeyVariable] = "yourValue";

Example 3: how to change input value in javascript using class

// Find the input element with a class of "bar" that is a direct child of a form with a name attribute of "foo"
document.querySelector("form[name='foo'] > input.bar").value = "hehe works"

Example 4: use value of variable as key javascript

var final = [{
  id: 23477234
}];


//add new object to the array using variables as keys AND values
var newArrray = {};
var key = "name";
var value = "John";
newArrray[key] = value;
final.push(newArrray);

/*
final now equals

[{
  id: 23477234,
  name: "John"
}]

*/

Example 5: how to use variable in js key

ES6 defines ComputedPropertyName
var thetop = "top",
    obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

Example 6: how to assign same value of a key to 2 different keys in output JSON jolt

[
    {
        "operation": "shift",
        "spec": {
            "survey": {
                "key": {
                    "@": [ "a.b.firstProperty", "a.b.secondProperty" ],
                    "#Constant": [ "a.b.thirdProperty", "a.b.fourthProperty" ]
                }
            }
        }
    }
]