How can I convert an array of objects to an object with key-value pairs in JavaScript?Richard W
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.
Similar Questions
How can I convert an object to an array of key-value pairs in JavaScript?
How can I convert a JavaScript object to an array of key-value pairs using Object.entries()?
How can I convert an object to a key-value pair array in JavaScript without using Object.entries()?
How can I convert an object to an array in JavaScript while preserving key-value pairs?
How can I convert an object to an array in JavaScript without losing keys?
How can I convert an array of objects to a CSV file in JavaScript?
How can I add a key-value pair to an object in JavaScript?
How can I convert an array-like object to an array in JavaScript?
How can I convert an object to query parameters in JavaScript?
How can I convert an object to query parameters in JavaScript?
How can I convert an object to a FormData object in JavaScript?
How do I convert an object to an array in JavaScript?
How can I convert a string to an array of characters in JavaScript?
How can I convert a string to an array of words in JavaScript?
How can I convert an object to a string in JavaScript?
How can I convert a string to an object in JavaScript?
How can I convert an object to a Map in JavaScript?
How can I convert an object to a set in JavaScript?
How can I convert an object to an XML string in JavaScript?
How can I sort an array of objects based on a property value in JavaScript?