Home > Web Front-end > JS Tutorial > How to Convert a JavaScript Array of Objects into a Single Object?

How to Convert a JavaScript Array of Objects into a Single Object?

Mary-Kate Olsen
Release: 2024-12-03 16:27:14
Original
415 people have browsed it

How to Convert a JavaScript Array of Objects into a Single Object?

Converting Array of Objects into a Single Object in JavaScript

In JavaScript, you may encounter situations where you need to consolidate an array of objects into a single encompassing object. For instance, you might have:

[
  { key: '11', value: '1100', $$hashKey: '00X' },
  { key: '22', value: '2200', $$hashKey: '018' }
];
Copy after login

and want to convert it into:

{
  "11": "1100",
  "22": "2200"
}
Copy after login

This transformation can be effortlessly accomplished using the reduce() method, as seen in the following snippet:

var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});

console.log(object)
Copy after login

The above is the detailed content of How to Convert a JavaScript Array of Objects into a Single Object?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template