Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Convert array of objects into hashmap

I have a set of values in an array where each value has an ID and LABEL.

Once I have the value array and type console value[0] and value[1], the output is:

value[0] 
Object {ID: 0, LABEL: turbo}

value[1] 
Object {ID: 1, LABEL: classic}

How can I store these values in a hash map like a key-value (ID-LABEL) pair, and store them in a json?

like image 335
casillas Avatar asked Dec 30 '25 14:12

casillas


1 Answers

This could be achieved by calling reduce on your array of values (ie data), to obtain the required hash map (where ID is the key and value is the corresponding LABEL):

const data = [
{ID: 0, LABEL: 'turbo'},
{ID: 1, LABEL: 'classic'},
{ID: 7, LABEL: 'unknown'}
];

const hashMap = data.reduce((result, item) => {
  return { ...result, [ item.ID ] : item.LABEL };
}, {});

const hashMapJson = JSON.stringify(hashMap);

console.log('hashMap', hashMap);
console.log('hashMapJson', hashMapJson);
 
/*
More concise syntax:
console.log(data.reduce((result, { ID, LABEL }) => ({ ...result, [ ID ] : LABEL }), {}))
*/
like image 110
Dacre Denny Avatar answered Jan 01 '26 02:01

Dacre Denny