2016-12-19 137 views
1

我一直在試圖使用標籤雲模塊從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] 
     });   
     }); 

回答

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

謝謝!有用! –

1

在普通的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)

0

試試這個。

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

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; 
}, []) 
相關問題