【问题标题】:Transmute array of objects to class instances将对象数组转换为类实例
【发布时间】:2017-08-09 13:34:34
【问题描述】:

我从 php 返回一个对象数组,我想将这些数据转换为 ContentData 类的实例。

我目前有以下可行的方法,但是我有一种直觉,有一种更清洁的方法可以实现结果。

return this.http.post("get-content.php", urlParams)
.map(this.extractData)
.map(array => {
    let newArray = Array<ContentData>();
    array.forEach(obj => {
        newArray.push(new ContentData().deserialize(obj));
    });
    return newArray;
})
.catch(this.handleError)

private extractData(res: Response): any {
    return res.json();
}

有没有比这样迭代数组数据更简洁的方法?


来自 php 的响应是:

[
{"id":"1","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null},
{"id":"2","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null}
]

预期的输出是[ContentData, ContentData, ...](只是一个一维数组)。

(2) [ContentData, ContentData]
0 : ContentData {content: "{"text": "<p>test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
1 : ContentData {content: "{"text": "<p>test test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
length : 2

【问题讨论】:

  • 我知道您希望 ContentData[][] 作为您的最终类型吗?
  • @MadaraUchiha 只是期待一维数组,我更新了问题以澄清这一点。
  • 这不是您当前返回的内容。好的,我去看看。
  • @MadaraUchiha 我已经用 php 请求的直接响应再次更新了问题。
  • 哦,等等,.map() 不是我想的那样。它不是[].map 甚至不是Bluebird.map(),它更类似于Promise 的.then()。我已经发布了答案,看看。

标签: angular typescript ecmascript-6


【解决方案1】:

如果我没看错你的代码,你可以做几件事:

  • 使用async 函数获得更线性的代码
  • 使用 .map() 而不是 for-and-push

类似这样的:

public async fetchAndProcess(/* args */) {
  try {
    const res = await this.http.post("get-content.php", urlParams); // Assuming fetch
    const json = await res.json();
    return result = json.map(item => new ContentData().deserialize(item));
  } catch (e) { this.handleError(e); }
}

我要做的另一件事是创建一个静态方法ContentData.fromSerialized() 或修改ContentData 的构造函数以接受item。但这更多是在代码风格领域。

【讨论】:

  • 我还没有使用async 实现任何东西 - 所以这需要我几分钟来处理。不过还是谢谢你的回答。
  • @Zze 当然可以,如果您需要澄清某些事情,请告诉 :)
  • 我不明白这是怎么回事...item 不等于响应中的数组吗?
  • 不,通常在谈论.map() 时,我们谈论的是Array.prototype.map(),它接受回调并迭代数组并将回调应用于每个项目,返回一个新数组。不知道你用的是什么monad库,不过json是数组,json.map()是处理循环。
  • 难怪我这么困惑.....它使用的是Observable.map()而不是Array.prototype.map()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2012-08-02
  • 2016-02-20
  • 1970-01-01
  • 2021-05-03
相关资源
最近更新 更多