Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 to make strings in an array become keys in objects within a new array in JavaScript. Let's consider a simple array:
let array = ['bike', 'car'];
We want to transform this array into a new array where each string becomes a key in an object with an empty array as its value:
let newArray = [{bike: []}, {car: []}];
Let's explore different methods to accomplish this transformation in JavaScript.
Using map() Method
The map() method creates a new array by calling a provided function on every element in the calling array. It's perfect for transforming array elements.
Syntax
array.map(function(currentValue, index, arr), thisValue)
Example: Basic Transformation
In this example, we use map() with computed property names to convert strings into object keys:
<!DOCTYPE html>
<html>
<body>
<p id="tutorial"></p>
<script>
let arr = ['bike', 'car'];
let newArr = arr.map(item => ({ [item]: [] }));
document.getElementById("tutorial").innerHTML = JSON.stringify(newArr);
</script>
</body>
</html>
[{"bike":[]},{"car":[]}]
Using for...of Loop
An alternative approach uses a traditional loop to build the new array step by step:
<!DOCTYPE html>
<html>
<body>
<p id="tutorial"></p>
<script>
let array = ['apple', 'orange'];
let newArray = [];
for(let item of array) {
let obj = {};
obj[item] = [];
newArray.push(obj);
}
document.getElementById("tutorial").innerHTML = JSON.stringify(newArray);
</script>
</body>
</html>
[{"apple":[]},{"orange":[]}]
Complete Example with Before and After
This example shows both the original array and the transformed result:
<!DOCTYPE html>
<html>
<body>
<p>Original array: <span id="original"></span></p>
<p>Transformed array: <span id="transformed"></span></p>
<script>
let values = ['studentNames', 'studentMarks'];
document.getElementById("original").innerHTML = JSON.stringify(values);
let convertedArray = values.map(item => ({ [item]: [] }));
document.getElementById("transformed").innerHTML = JSON.stringify(convertedArray);
</script>
</body>
</html>
Original array: ["studentNames","studentMarks"]
Transformed array: [{"studentNames":[]},{"studentMarks":[]}]
Key Points
- Use computed property names
[variable]to create dynamic object keys - The
map()method is more concise and functional - The loop approach gives more control over the transformation process
- Both methods create a new array without modifying the original
Conclusion
Converting array strings to object keys is easily accomplished using map() with computed property names. This technique is useful for creating structured data from simple arrays, especially when building configuration objects or preparing data for APIs.
