将响应对象数组转置到另一个不同的对象数组

时间:2017-03-27 10:25:35

标签: angular typescript

我试图弄清楚如何将响应转换为我为存储创建的界面。

interface TestInterface {
name: string,
count: number
}

http.get("localhost:8088/api/getdata")
.map(res => res.json()
.subscribe(
(data) => {

// transpose the response into array of TestInterface

});

响应以下列格式返回对象数组:

[
  {
    "Id": "54d130ce-0812-e711-b861-f01faf23929d",
    "Name": "First Name Attempt",
    "Description": "asd",
    "Count": 5
  },
  {
    "Id": "6f08ca4a-0d12-e711-b861-f01faf23929d",
    "Name": "Second Attempt",
    "Description": "One Site",
    "Count": 3
  }
]

1 个答案:

答案 0 :(得分:2)

像这样手动执行

interface TestInterface {
  name: string,
  count: number
}

http.get("localhost:8088/api/getdata")
  .map(res => res.json())
  .map((data: any[]) => {
    let arr: TestInterface[] = [];
    data.forEach(o => {
      let obj: TestInterface = {};
      obj.name = o.Name;
      obj.count = o.Count;
      arr.push(obj);
    });
    return arr;
  })
  .subscribe((data: TestInterface[]) => {
    // data here

  });