JavaScript:将对象数组转换为hashmap

时间:2019-06-25 04:05:22

标签: javascript typescript

我在数组中有一组值,其中每个值都有一个IDLABEL

一旦我有了值数组并输入console value[0]value[1],输出为:

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

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

如何将这些值存储在像键值对(ID-LABEL)对的哈希图中,并将它们存储在json中?

4 个答案:

答案 0 :(得分:3)

这可以通过在值数组(即data)上调用reduce以获得所需的哈希映射(其中ID是键,而值是相应的{ {1}}):

LABEL

答案 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"]