key value javascript code example

Example 1: for key value in object javascript

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

Example 2: js key value array

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}

Example 3: javascript add to object

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

// Array of Objects in form {element: {id: 10, quantity: 10} }
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

Example 4: array of array key value javascript

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

Example 5: how to use variable in js key

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

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