Convert object array to hash map, indexed by an attribute value of the Object
This is fairly trivial to do with Array.prototype.reduce
:
var arr = [ { key: 'foo', val: 'bar' }, { key: 'hello', val: 'world' }];var result = arr.reduce(function(map, obj) { map[obj.key] = obj.val; return map;}, {});console.log(result);// { foo:'bar', hello:'world' }
Note: Array.prototype.reduce()
is IE9+, so if you need to support older browsers you will need to polyfill it.
Using ES6 Map (pretty well supported), you can try this:
var arr = [ { key: 'foo', val: 'bar' }, { key: 'hello', val: 'world' }];var result = new Map(arr.map(i => [i.key, i.val]));// When using TypeScript, need to specify type:// var result = arr.map((i): [string, string] => [i.key, i.val])// Unfortunately maps don't stringify well. This is the contents in array form.console.log("Result is: " + JSON.stringify([...result])); // Map {"foo" => "bar", "hello" => "world"}
You can use the new Object.fromEntries()
method.
Example:
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) // {a: b, x: y}