![](/img/trans.png)
[英]Javascript: Trying to access elements of a JSON array gives me individual characters
[英]Iterating over array of JSON objects in TypeScript gives me individual characters at indices
我有一个从API调用接收到的JSON对象数组。
data = [{
"notificationId": null,
"notificationText": "xXXX YYY",
"notificationType": "typeA",
"fromId": 2,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898875,
"nano": 0
}},
{
"notificationId": null,
"notificationText": "YYYYYYY,
"notificationType": "typeB",
"fromId": 3,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898903,
"nano": 0
}}
]
我希望通过遍历此数组来获得各个Notification对象,我的Notification接口如下所示
interface Notification {
notificationId: number;
notificationText : string;
notificationType : string;
fromId:number;
toId:number;
timestampCreated: Date ;
}
notif: Notification[] = [];
.
.
this.notif =data;
for(var i=0;i<this.notif.length ;i++){
console.log("notification text at "+this.notif[i].notificationText);
//this gives undefined
//and it loops through all the characters of the data
// not just twice
}
可以帮忙,我对angular2 /打字稿世界很陌生。
当我找出问题所在时,我正在回答这个问题。 在以上代码段中,对象数组实际上是JS对象而不是JSON对象的数组。 因此,我需要先解析这些对象,然后才能将它们用作JSON。 一个简单的JSON.parse(data)解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.