javascriptangulartypescripttag-cloud

How to transform Object into Array with key and values?


I have been trying to use the tag cloud module from https://github.com/d-koppenhagen/angular-tag-cloud-module and my data object is like this:

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

According to the module's guide, the data array should insert like this below:

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

My code is at below, just recently coding with Typescript and hope someone can give me a hint!

 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]
        });           
      });

Solution

  • If post['tags'] is:

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

    Then you need to do:

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