1

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

4 Answers 4

1

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] });
});
Sign up to request clarification or add additional context in comments.

Comments

1

In plain Javascript, you could use Array#map and take the the keys of the object for text and the value for 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)

Comments

0

Try this.

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.