Home > Article > Web Front-end > How to Convert an Array of Objects into a Single Object with Key-Value Pairs?
How to Transform an Array of Objects into an Object with Key-Value Pairs
Problem:
Given an array of objects, the task is to convert it into a single object where each object's properties serve as keys, and their corresponding values become the values of the resulting object. For instance, an array like [{"name1":"value1"}, {"name2":"value2"}] should be converted into {"name1":"value1", "name2":"value2"}.
Solution:
To achieve this transformation, the most efficient approach is to leverage JavaScript's Object.assign() method. This method allows you to create a new object by merging the properties of multiple source objects. By combining Object.assign() with the spread syntax (...), you can spread the elements of the input array into the target object:
const array = [{"name1":"value1"}, {"name2":"value2"}]; const object = Object.assign({}, ...array); console.log(object); // {"name1":"value1", "name2":"value2"}
This solution is widely supported by most modern browsers, ensuring compatibility across platforms.
The above is the detailed content of How to Convert an Array of Objects into a Single Object with Key-Value Pairs?. For more information, please follow other related articles on the PHP Chinese website!