2016-12-19 5 views
1

私はhttps://github.com/d-koppenhagen/angular-tag-cloud-moduleからタグクラウドモジュールを使用しようとしていると私のデータオブジェクトは、このようなものです:キーと値を使ってObjectをArrayに変換する方法は?

{ "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 } 

次にあなたがする必要がある:プレーンJavaScriptでは

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

ありがとう!できます! –

1

、あなたは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; 
}, []) 
関連する問題