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.