【问题标题】:How to transform Object into Array with key and values?如何将对象转换为具有键和值的数组?
【发布时间】:2016-12-19 09:15:34
【问题描述】:

我一直在尝试使用https://github.com/d-koppenhagen/angular-tag-cloud-module的标签云模块,我的数据对象是这样的:

{ "Speech": 4, "E-commerce": 1, "Meeting": 1, "Garena": 1 , "Silicon valley": 1}

根据模块的指南,数据数组应该像下面这样插入:

[ {text: "Speech", weight: 4}, {text: "E-commerce", weight: 1}, {text: "Meeting", weight: 1},{text: "Garena", weight: 1}, {text: "Sillicon valley", weight: 1}]

我的代码在下面,最近用Typescript编码,希望有人能给我提示!

 var post_tags: Array<string> = post['tags'];

      post_tags.forEach(element => {
        this.counts[element] = ( this.counts[element] || 0)+1;
        this.tags.push({
          text: Object.keys(this.counts),
          weight: this.counts[element]
        });           
      });

【问题讨论】:

    标签: javascript angular typescript tag-cloud


    【解决方案1】:

    如果post['tags'] 是:

    { "Speech": 4, "E-commerce": 1, "Meeting": 1, "Garena": 1 , "Silicon valley": 1 }
    

    那你需要做的:

    let normalized = [] as { text: string, weight: number }[];
    Object.keys(post['tags']).forEach(tag => {
        normalized.push({ text: tag, weight: post['tags'][tag] });
    });
    

    【讨论】:

      【解决方案2】:

      在纯 Javascript 中,您可以使用 Array#map 并获取 text 的对象键和 weight 的值。

      var object = { Speech: 4, "E-commerce": 1, Meeting: 1, Garena: 1 , "Silicon valley": 1},
          array = Object.keys(object).map(function (k) {
              return { text: k, weight: object[k]};
          });
      
      console.log(array)

      【讨论】:

        【解决方案3】:

        试试这个。

        var post_tags = { "Speech": 4, "E-commerce": 1, "Meeting": 1, "Garena": 1 , "Silicon valley": 1}
        
        var array = [];
        
        Object.keys(post_tags).forEach( function(k,v){ // iterate over the object keys
          
              var obj = {};
              obj["text"] = k;
              obj["weight "] = post_tags[k]
              array.push(obj);
        });
        
        
        console.log(array);

        【讨论】:

          【解决方案4】:
          interface PostTags {
            text: string;
            weight: number;
          }
          
          post['tags'] = { "Speech": 4, "E-commerce": 1, "Meeting": 1, "Garena": 1 , "Silicon valley": 1};
          
          const array: Array<PostTags> = Object.keys(post['tags']).reduce((acc, tag) => {
             acc.push({
               text: tag, 
               weight: post['tags'][tag]
             }); 
             return acc;
          }, [])
          

          【讨论】:

            猜你喜欢
            • 2017-09-23
            • 1970-01-01
            • 1970-01-01
            • 2018-08-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多