casillas
casillas

Reputation: 16793

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?

Upvotes: 3

Views: 4325

Answers (4)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92377

Try (where h={})

data.map(x=> h[x.ID]=x.LABEL );

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

let h={}
data.map(x=> h[x.ID]=x.LABEL );

console.log(h);

Upvotes: 2

Dacre Denny
Dacre Denny

Reputation: 30360

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 }), {}))
*/

Upvotes: 3

Andra
Andra

Reputation: 1382

You can use forEach method.

> var hmap = {};
undefined
> var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}]
undefined
> value.forEach(function(element){
... hmap[element.ID] = element.LABEL;
... });
> hmap
{ '0': 'turbo', '1': 'classic' }

or

var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}]
var hmap = {};
value.forEach(function(element){
    hmap[element.ID] = element.LABEL;
});
console.log(hmap);

Upvotes: 1

twomarktwo
twomarktwo

Reputation: 342

You can iterator over each item in the array, and use the ID proeprty as a javascript objects key and the LABEL as the value.

var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}];

let theNewMap = {};
for(var i = 0; i < value.length; i++) {
  theNewMap[value[i].ID] = value[i].LABEL;
}

// theNewMap Should now be a map with 'id' as key, and 'label' as value
console.log(JSON.stringify(theNewMap ))

Upvotes: 1

Related Questions