将标签转换为标签数组

Converting Tags to Array of Tags

我找到了一些代码,用于通过打字稿将标签值分配给 AWS 中的资源。问题是,其中一个资源(自动缩放组)处理标签的方式与所有其他资源不同。我没有两次定义我所有的标签值,而是试图找出一种编程方式来做到这一点。

这是我当前的标签变量:

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",
    }
  ];

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

您可以像这样.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);

我发现 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 }));