create key value pair object 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: how to add field to object in js

// original object { key1: "a", key2: "b"}
var obj = {
    key1: "a",
    key2: "b"
};

// adding new filed - you can use 2 ways
obj.key3 = "c"; // static
// or
obj["key3"] = "c"; // dynamic - 'key3' can be a variable
console.log(obj) // {key1: "a", key2: "b", key3: "c" }

Example 3: key value pair array in javascript

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

Example 4: js add data in object

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

Example 5: javascript create object from key value pairs

let items = 'key1:value1;key2:value2;key3:value3';
let items_array = items.split(';');
let final_items = items_array.map(item => item.split(':'));
// [ [ key1, value1 ], [ key2, value2 ], [ key3, value3 ] ]

let final_result = Object.fromEntries(final_items);
// { "key1" : "value1", "key2" : "value2", "key3" : "value3" }