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?

2

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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 ))

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.