0

我找到了一些代码,用于通过打字稿将标签值分配给 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",
    }
  ];

我是打字稿的新手,但我敢肯定,几乎只有一个班轮可以做到这一点。apply我在考虑一个 for 循环和字符串,但我确信我缺少某种和重定向。

4

2 回答 2

0

我发现ES2017不喜欢打字。所以我不得不将标签更改为 type 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 }));
于 2019-06-20T14:42:40.440 回答
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);

于 2019-06-19T23:26:06.680 回答