我在数组中有一组值,其中每个值都有一个ID和LABEL。
一旦我有了值数组并输入了console value[0]和value[1],输出就是:
value[0]
Object {ID: 0, LABEL: turbo}
value[1]
Object {ID: 1, LABEL: classic}如何像键值(ID-标签)对一样将这些值存储在散列映射中,并将它们存储在json中?
发布于 2019-06-25 04:14:15
这可以通过调用值数组上的reduce (即data)来获得所需的哈希映射(其中ID是键,值是对应的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 }), {}))
*/
发布于 2019-06-25 05:37:49
尝试(其中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);
发布于 2019-06-25 04:13:59
您可以迭代数组中的每个项,并使用ID proeprty作为javascript对象key和LABEL作为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 ))
https://stackoverflow.com/questions/56746693
复制相似问题