男孩和女孩,我在同一个问题上挣扎了很多次。
我使用此请求:
const url = this.getTheRightEndpoint(tag.name);
this.httpClient.post(url, this.report, { headers: new HttpHeaders({ 'Authorization': 'BEARER ' + this.auth.getUserSession().access_token }), responseType: 'json'}).subscribe((data: Array<string>) => {
console.log(data);
console.log(JSON.parse(data));
});
}
,在第一个控制台日志上,我获得:
[{"BackOrder":"0","BadAddress":"0","CalculatePerfectCompletationTotal":"100 %","CancelByCustomer":"0","Completed":"4","CustomerRelatedException":"0 %","Damage":"0","DeliveryRelatedException":"0 %","DriverName":"Rolly's Transfer","FillRate":"100 %","NoFit":"0","NotAtHome":"0","OrderWithError":"0","PathNotClear":"0","PerfectCompletedStop":"4","PickupDate":"2018-12-04","PlannedStop":"4","Rescheduled":"0","RouteDelay":"0","RouteName":"","TruckNumber":"401","UnableReachCustomer":"0","UnfilteredPlannedStop":"4","Unknown":"0","WrongDate":"0"}]
我尝试这样解析它(第二个consol.log):console.log(JSON.parse(data)); 然后我得到了:
0: {BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "100 %", CancelByCustomer: "0", Completed: "4", …}
1: {BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "100 %", CancelByCustomer: "0", Completed: "4", …}
2: {BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "83 %", CancelByCustomer: "0", Completed: "6", …}
以此类推...
但是我的目标是遍历该对象以达到每个“行”的属性……但是我做不到……我尝试过使用foreach循环的许多示例,但是响应是data.foreach是不是函数...所以我迷路了,因为foreach函数是我的编辑器提出的。
有人可以帮我吗? 谢谢。
答案 0 :(得分:0)
我将其分解为下面的最简单形式,我们在其中循环一个标准数组,然后从对象中提取数据:-
我刚刚为您拉出了对象的Completed
部分,以便您了解如何操作。
let data = [
{BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "100 %", CancelByCustomer: "0", Completed: "4"},
{BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "100 %", CancelByCustomer: "0", Completed: "4"},
{BackOrder: "0", BadAddress: "0", CalculatePerfectCompletationTotal: "83 %", CancelByCustomer: "0", Completed: "6"}]
for (let i = 0; i < data.length; i++) {
console.log(data[i].Completed);
}
因此,对于您的代码,您将需要使用以下脚本:-
const url = this.getTheRightEndpoint(tag.name);
this.httpClient.post(url, this.report, { headers: new HttpHeaders({ 'Authorization': 'BEARER ' + this.auth.getUserSession().access_token }), responseType: 'json'}).subscribe((data: Array<object>) => {
console.log(data);
for (let i = 0; i < data.length; i++) {
console.log(data[i]. Completed);
}
});
}
也请注意,从您的data
返回的subscribe
应该是data: Array<object>
,因为返回的是对象数组而不是字符串。
答案 1 :(得分:0)
您可以这样做:
let json = JSON.parse(data);
json.forEach((v) => { console.log(v); });
如果数据是对象数组,请执行以下操作:
let json = [];
JSON.parse(data).forEach((v) => { json.push(v); });
json.forEach((v) => { console.log(v); });
答案 2 :(得分:0)
一种奇怪的行为。您的第一个输出完全看起来像一个数组,但是“ data.foreach不是函数”使我认为data
不是Array.prototype实例。您可以尝试使用JSON.parse(JSON.stringify(data))
使JSON库将您的数据突变为数组,然后将其映射。尝试这样的事情:
this.httpClient.post(...args).subscribe(data => {
let _data = JSON.parse(JSON.stringify(data)).map(row => Object.values(row));
console.log(_data);
});
}
这是一个丑陋的解决方法,但我希望它会有所帮助