object key value pairs code example

Example 1: iterate key value object javascript

'use strict';
// ECMAScript 2017
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

Example 2: javascript iterate over object keys and values

const object1 = {
  a: 'somestring',
  b: 42
};

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

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed

Example 3: for key value in object javascript

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

Example 4: 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" }