将标签转换为标签数组

时间:2019-06-19 23:15:13

标签: typescript pulumi

我找到了一些代码,用于通过打字稿将标签值分配给AWS中的资源。问题是,其中一种资源(autoScaling组)对标签的处理方式与所有其他资源不同。而不是两次定义所有标签值,我试图找到一种编程的方式来实现它。

这是我当前的标签变量:

const tags = [{
  Name: "ServerName"
  tContact: "john@doe.com"
  tEnv: "DEV"
  tOwner: "John doe",
  tProject: "Typescript",
}];

如果我要为其他代码类型手动创建第二个,则应该是:

const tags2 = 
   [
    {
      key: "Name",
      propagateAtLaunch: true,
      value: "ServerName",
    },
    {
      key: "tContact",
      propagateAtLaunch: true,
      value: "john@doe.com",
    },
    {
      key: "tEnv",
      propagateAtLaunch: true,
      value: "DEV",
    },
    {
      key: "tOwner",
      propagateAtLaunch: true,
      value: "John Doe",
    },
    {
      key: "tProject",
      propagateAtLaunch: true,
      value: "Typescript",
    }
  ];

我是打字稿的新手,但我敢肯定甚至有将近一个班轮来做打字稿。我当时在考虑for循环和字符串,但是我确定我缺少某种apply和重定向。

2 个答案:

答案 0 :(得分:0)

您可以.map这样的对象条目Object.entries

Object.entries(tags[0]).map(([key, value]) => (
      {
        key: key, 
        value: tags[0][key], 
        propagateAtLaunch: true
      }));

const tags = [{
  Name: "ServerName",
  tContact: "john@doe.com",
  tEnv: "DEV",
  tOwner: "John doe",
  tProject: "Typescript",
},
{
  Name: "ServerName1",
  tContact: "john@doe.com",
  tEnv: "DEV1",
  tOwner: "John doe",
  tProject: "Typescript",
}];
//let obj = tags[0];
//console.log(obj)
let results = [];
let result = tags.forEach(c=> results.push(Object.entries(c).map(([key, value]) => ({key: key, value: tags[0][key], propagateAtLaunch: true}))));
console.log(results);

答案 1 :(得分:0)

我发现 ES2017 不喜欢打字。因此,我不得不将标签更改为any类型。

const tags: any = [{
  Name: "ServerName",
  tContact: "john@doe.com",
  tEnv: "DEV",
  tOwner: "John doe",
  tProject: "Typescript",
}

然后我使用了第一次提交的代码:

let result = Object.entries(tags[0]).map(([key, value]) => 
  ({ key: key, value: tags[0][key], propagateAtLaunch: true }));