How to create an object from the given key-value pairs using JavaScript?

You are given different key-value pair(s), in any form like an array, and using those key-value pairs you need to construct an object which will have those key-value pairs.

Object{} => Object {
"0" : "Geeksforgeeks",
"1" : "Hello JavaScript",
"2" : "Hello React"
}

We first need to declare an empty object, with any suitable name, then by using various JavaScript techniques and methods, we need to insert the given key-value pairs into the previously created empty object.

Let us first try to understand how we could create an empty object in JavaScript. Creating an empty object in JavaScript could be achieved in several ways.

Example1:

let object = {};
console.log(object);
Output:
{}

Example2:

let object = new Object();
console.log(object);
Output:
{}

Now after creating the object now we are going to analyze the approaches through which we could add the given key-value pair (s) in that previously created empty object.

<script>  
  let object = {};
  let firstKey = 0;
  let firstKeyValue = "GeeksforGeeks";
  let secondKey = 1;
  let secondKeyValue = "Hello JavaScript";
  let thirdKey = 2;
  let thirdKeyValue = "Hello React";
  
  object[firstKey] = firstKeyValue;
  object[secondKey] = secondKeyValue;
  object[thirdKey] = thirdKeyValue;
  console.log(object);
</script>

Output:

{ "0": "GeeksforGeeks", "1": "Hello JavaScript", "2": "Hello React" }

Leave a comment

Your email address will not be published. Required fields are marked *