【问题标题】:JavaScript: Convert array of objects into hashmapJavaScript:将对象数组转换为哈希图
【发布时间】:2019-06-25 04:05:22
【问题描述】:

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

一旦我有了值数组并输入控制台value[0]value[1],输出是:

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

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

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

【问题讨论】:

标签: javascript typescript


【解决方案1】:

尝试(其中 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);

【讨论】:

    【解决方案2】:

    这可以通过在值数组(即data)上调用reduce 来实现,以获得所需的哈希映射(其中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 }), {}))
    */

    【讨论】:

      【解决方案3】:

      您可以对数组中的每个项目进行迭代,并将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 ))

      【讨论】:

        【解决方案4】:

        您可以使用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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-27
          • 2019-05-23
          • 2012-10-29
          相关资源
          最近更新 更多