如何在打字稿中创建包含多个键值对的对象数组

时间:2020-04-22 12:21:11

标签: typescript

我从服务器收到的响应如下图所示:

[
    {_from: "A/1", _to: "A/2", status:"ok"},
    {_from: "A/2", _to: "A/3", status:"ok"},
    {_from: "A/1", _to: "A/3", status:"ok"}
]

我想将其转换为数组,如下所示,在 Typescript 中:

[
    {from: 1, to: 2},
    {from: 2, to: 3},
    {from: 1, to: 3}
]

我是TypeScript的新手,对键值对的概念感到困惑。对此,我们将给予任何帮助。谢谢!

1 个答案:

答案 0 :(得分:-2)

这是使用JavaScript / TypeScript的Array.map()的方法。您可以遍历数组,拆分值,然后返回所需的对象。

const a = [{_from: "A/1", _to: "A/2", status:"ok"},
{_from: "A/2", _to: "A/3", status:"ok"},
{_from: "A/1", _to: "A/3", status:"ok"}];

const res = a.map(({_from, _to}) => ({
  from: (_from.split('/'))[1],
  to: (_to.split('/'))[1],
}));

console.log(res);