javascript - 如何将对象转换为具有键和值的数组?

标签 javascript angular typescript tag-cloud

我一直在尝试使用来自 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]
        });           
      });

最佳答案

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

关于javascript - 如何将对象转换为具有键和值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219219/

相关文章:

javascript - 类型错误 : Cannot read property 'name' of undefined

javascript - 在 Nodejs 中解析大型 JSON 文件

javascript - 如何使用 Mirth Connect 3.4.1 将 json 转换为 HL7?

angular - 如何在 XmlHttpRequest 中使用 Angular 拦截器

node.js - Node/Angular 2 : Update navbar and show sidebar after user login

typescript - 有没有办法禁用 Typescript 2.4 版引入的弱类型检测?

javascript - firestore 获取五个具有更多子集合数量的文档

angular - 从 Docker 运行 Angular 测试脚本

typescript - 导入核心函数

typescript - 如何为具有默认导出的模块编写类型定义