在Angular 7应用程序中,我具有以下内容:
var name_key = "name";
var language_key = "language";
var type_key = "type"
然后,API返回以下JSON:
{
"errors": {
"language": [
"language not found"
],
"name": [
"name not found",
"name must not exceed 200 characters"
]
}
}
我需要获取每个key
的错误消息,这样就可以了:
"name" > "name not found",
"name must not exceed 200 characters"
"language" > "language not found"
"type" > NULL
我该怎么做?
答案 0 :(得分:1)
看起来就是您所需要的,类似数组的语法允许您使用变量键访问对象字段:
const apiResponse = getApiData(); //your API response
const errorKeys = [name_key, language_key, type_key];
let errors = [];
for (let errKey of errorKeys) {
errors.push(apiResponse.errors[errKey]);
}
P.S .:您通常不会在打字稿中使用var
关键字,因为它会弄乱范围。使用let或const代替here's why