Make strings in array become keys in object in a new array in JavaScript?


The task we are going to perform in this article is make strings in array become keys in object in a new array in JavaScript. Let’s consider a simple array −

let array= ['bike', 'car']

Now, we are going to use map() to convert the above array to a new array (keys in an object). The array will then look like this −

let newArray= [{shorts: []},{tees: []}, ]

Let’s dive into the article to learn more about on making a strings in array become keys in object in a new array in JavaScript.

Using map()

The map() method builds a new array from the contents of the calling array after performing a given function on each element.

Syntax

Following is the syntax for map()

array.map(function(currentValue, index, arr), thisValue)

For getting better understanding Let’s look into the following examples of making a strings in array become keys in object in a new array

Example

In the following example we are running the script using map() to convert strings in array to become keys in object.

<!DOCTYPE html>
<html>
   <body>
      <p id="tutorial"></p>
      <script>
         let arr = ['bike', 'car'];
         let newArr = arr.map(a => ({ [a]: [] }));
         document.getElementById("tutorial").innerHTML=JSON.stringify(newArr);
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of an array printed on the webpage that was activated by the event that got triggered on executing the script.

Example

Following is another example

<!DOCTYPE html>
<html>
   <body>
      <p id="tutorial"></p>
      <script>
         let array= ['Bheem', 'Ram']
         let newarray = [];
         for(let item of array) {
            let obj = {};
            obj[item] = [];
            newarray.push(obj)
         }
         document.getElementById("tutorial").innerHTML=JSON.stringify(newarray);
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying the array printed on the webpages as a result of an event that gets triggered on running the script.

Example

Execute the below code to observe how map() was used for converting array string to become keys in object.

<!DOCTYPE html>
<html>
   <body>
      <p id="tutorial"></p>
      <p id="tutorial1"></p>
      <script>
         var values = ['studentNames', 'studentMarks'];
         document.getElementById("tutorial").innerHTML=JSON.stringify(values);
         var convertIntoNewArray = values.map(arrayObject => ({ [arrayObject]: [] }));
         document.getElementById("tutorial1").innerHTML=JSON.stringify(convertIntoNewArray);
      </script>
   </body>
</html>

When the script gets executed, the event gets triggered and displays an actual array and a changed array on the webpage.

Updated on: 21-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements