Categories
JavaScript Answers

How to convert object array to hash map, indexed by an attribute value of the object with JavaScript?

Spread the love

To convert object array to hash map, indexed by an attribute value of the object with JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const array = [
  { key: "a", value: "b", redundant: "aaa" },
  { key: "x", value: "y", redundant: "zzz" },
];

const hash = Object.fromEntries(array.map((e) => [e.key, e.value]));

console.log(hash);

to call array.map to map the entries to an array of key-value pair arrays with the callback.

Then we call Object.fromEntries to convert the array to an object with the key as the property key and the values as the property values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *