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
Mary-Kate OlsenOriginal
2024-12-03 16:27:14417browse

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' }
];

and want to convert it into:

{
  "11": "1100",
  "22": "2200"
}

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)

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!

Statement:
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