【发布时间】:2013-08-28 12:41:42
【问题描述】:
我有一个 JavaScript 函数,它对 API 进行 ajax 调用,并获取一个 JSON 数组。
这是我得到的一个数组示例:
[
{
"ErrorType": "Errors",
"Explanations": [
{
"Explanation": "Price Missing",
"Locations": [
25,
45
]
},
{
"Explanation": "Unit of measurement not valid",
"Locations": [
25,
301,
302
]
}
]
},
{
"ErrorType": "Warnings",
"Explanations": [
{
Blablabla,
Ithinkthere's already much here
}
]
}
]
我把它放到了一个 JavaScript 数组中:
$scope.CorrectionDatas = ResponseFromApi;
所以,对于每个 ErrorType,我都有一些“解释”。我想添加另一个属性,以便拥有这样的东西:
[
{
"ErrorType": "Errors",
"Explanations": [
{
"Explanation": "Price Missing",
"Locations": [
25,
45
]
},
{
"Explanation": "Unit of measurement not valid",
"Locations": [
25,
301,
302
]
}
],
"show": true
},
{
"ErrorType": "Warnings",
"Explanations": [
{
Blablabla,
Ithinkthere's already much here
}
],
"show":true
}
]
我认为只有这样才能做到这一点:
$scope.CorrectionDatas.forEach(function (error) {
error.push({ show: true });
});
但是我的调试器给了我一个错误:
Error: error.push is not a function
$scope.getErrors/</<@http://localhost:1771/dependencies/local/js/Correction/CorrectionCtrl.js:26
【问题讨论】:
-
问题在于,虽然 JSON 响应构成一个数组,但该数组的每个元素都是一个对象,而不是一个数组。即
{"ErrorType":"Warnings", "Explanations":[{ Blablabla, I think there's already much here }]}是一个对象... -
你能显示'typeof error'的输出吗?我相信这是一个对象,而不是一个数组。
-
据说,我收到了一个对象,谢谢你的帮助
标签: javascript arrays json angularjs