How to transform Object into Array with key and values?

1.6k views Asked by At

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

There are 4 answers

0
Nitzan Tomer On BEST ANSWER

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] });
});
0
Bazinga On
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;
}, [])
0
Nina Scholz On

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)

0
Deep On

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