3

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?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
casillas
  • 16,351
  • 19
  • 115
  • 215
  • Learn about what JSON is, understand that all JavaScript objects, including arrays and functions, are morally hash tables, and your question will disappear because it won't even make sense to you. – Aluan Haddad Jun 25 '19 at 04:14
  • 1
    Does this answer your question? [Convert object array to hash map, indexed by an attribute value of the Object](https://stackoverflow.com/questions/26264956/convert-object-array-to-hash-map-indexed-by-an-attribute-value-of-the-object) – superjos Feb 01 '22 at 10:03

4 Answers4

3

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 }), {}))
*/
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
2

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);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

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 ))
twomarktwo
  • 332
  • 1
  • 11
1

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);
Andra
  • 1,282
  • 2
  • 11
  • 34