How can I convert an array of objects to an object with key-value pairs in JavaScript?
Richard W
richard w profile pic

To convert an array of objects to an object with key-value pairs in JavaScript, you can use thereduce() method. Here's how you can do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

const array = [
  { key: 'name', value: 'John' },
  { key: 'age', value: 30 },
  { key: 'city', value: 'London' }
];

const result = array.reduce((obj, item) => {
  obj[item.key] = item.value;
  return obj;
}, {});

console.log(result);
// Output: { name: 'John', age: 30, city: 'London' }

In the example above, thereduce() method is called on thearray of objects. The initial value for the accumulator is an empty object{}. Inside the reducer function, for each item in the array, we assign thevalue of the object to the correspondingkey in the accumulator object. The final result is an object with key-value pairs extracted from the array. Using thereduce() method allows you to transform an array of objects into a single object with key-value pairs. The keys are obtained from thekey property of each object, and the values are obtained from thevalue property. You can customize the structure of the resulting object by modifying the logic inside the reducer function.