Languages
[Edit]
EN

JavaScript - convert array of objects to hash map (indexed by property value)

0 points
Created by:
Lani-Skinner
748

In this article, we would like to show you how to convert an array of objects to a hash map in JavaScript.

Quick solution (ES6+):

// ONLINE-RUNNER:browser;

const array = [{ key: 1, value: 'a' }, { key: 2, value: 'b' }];

const result = array.reduce((map, object) => ((map[object.key] = object.value), map), {});

console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }

 

Practical example

In this example, we use reduce() method to convert an array of objects into a hash map containing key/value pairs created with property values.

// ONLINE-RUNNER:browser;

var array = [
    { key: 1, value: 'a' },
    { key: 2, value: 'b' }
];

var result = array.reduce(function(map, object) {
    map[object.key] = object.value;
    return map;
}, {});

console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }

 

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - convert array of objects to hash map (indexed by attribute value)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join