typescript - JavaScript: Nesne dizisini hashmap'e dönüştür


Bir dizide her bir değerin bir ID ve LABEL değeri olduğu bir değer setim var.

Bir kez değer dizisine sahip olduğumda ve konsolda value[0] ve value[1] yazdırdığımda, çıktı şudur:

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

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

Bu değerleri bir anahtar-değer (ID-ETİKET) çifti olarak bir hash haritasında nasıl saklayabilirim ve bunları bir JSON dosyasında nasıl depolayabilirim?

Cevap #1

Bu, gerekli hash haritasını elde etmek için değerler dizinizde (örneğin data) reduce çağrısı yapılarak gerçekleştirilebilir (burada ID anahtar ve değer ilgili LABEL olur):

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

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

İlgili makaleler