我在数组中有一组值,其中每个值都有一个ID
和LABEL
。
一旦我有了值数组并输入console value[0]
和value[1]
,输出为:
value[0]
Object {ID: 0, LABEL: turbo}
value[1]
Object {ID: 1, LABEL: classic}
如何将这些值存储在像键值对(ID-LABEL)对的哈希图中,并将它们存储在json中?
答案 0 :(得分:3)
答案 1 :(得分:1)
您可以迭代数组中的每个项目,并将ID
属性用作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 ))
答案 2 :(得分:1)
您可以使用forEach方法。
> 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' }
或
var value = [{ID: 0, LABEL: "turbo"}, {ID: 1, LABEL: "classic"}]
var hmap = {};
value.forEach(function(element){
hmap[element.ID] = element.LABEL;
});
console.log(hmap);
答案 3 :(得分:1)
尝试(其中h = {})
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);
type A []interface{}
var x = map[string]interface{}{
"hello":"a",
"world":A{"b","c"},
}
y := x["world"]