To map an array to an object in JavaScript, you can use the reduce()
method. The reduce()
method applies a function to each element of the array and accumulates the result.
This method can be used to convert an array of objects to an object with key-value pairs.
const newArray = array.reduce((accumulator, currentValue) => {
// your logic here
}, initialValue);
In the above syntax:
array
is the original array you want to map.accumulator
is the accumulated result of each iteration. This is where you’ll be building your new object.currentValue
is the current element of the array that’s being processed.initialValue
is the initial value of the accumulator. This is optional, and if omitted, the first element of the array will be used as the initial value.
Map array to object JavaScript example
A simple example code demonstrates how to map an array of objects to an object with key-value pairs:
<!DOCTYPE html>
<html>
<body>
<script>
const arr = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const obj = arr.reduce((acc, cur) => {
acc[cur.id] = cur.name;
return acc;
}, {});
console.log(obj);
</script>
</body>
</html>
Output:
Another example
Let’s say you have an array of student objects, and each student has a name
and a score
property:
const students = [
{ name: 'Alice', score: 80 },
{ name: 'Bob', score: 90 },
{ name: 'Charlie', score: 95 }
];
You want to create a new object where the keys are the student names, and the values are their scores. You can achieve this using the reduce()
method:
const studentScores = students.reduce((obj, student) => {
obj[student.name] = student.score;
return obj;
}, {});
console.log(studentScores);
Output: { Alice: 80, Bob: 90, Charlie: 95 }
Comment if you have any doubts or suggestions on this JS Map topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version