Home > Web Front-end > JS Tutorial > How to Convert an Array of Objects into a Single Object with Key-Value Pairs?

How to Convert an Array of Objects into a Single Object with Key-Value Pairs?

DDD
Release: 2024-11-09 10:43:02
Original
436 people have browsed it

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"}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template