I have a set of values in an array where each value has an ID and 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);
But if I have the following json object where key is slightly different, it does not handle of course. I wonder how I could able to make the above solution in more generic to tackle different inputs.
const data = [
{K_ID: 0, K_LABEL: 'turbo'},
{L_ID: 1, K_LABEL: 'classic'},
{S_ID: 7, K_LABEL: 'unknown'}
];
IDandLABEL? please add the wanted result as well.ANYTHING_IDandANYTHING_LABELconst normalizedData = data.map( obj => ({ [obj[Object.keys( obj ).find( key => /_ID$/.test(key) )]]: obj[Object.keys( obj ).find( key => /_LABEL$/.test(key) )] }) );, then convert it to a map the same way you already do:const hashMap = nomalizedData.reduce( ...