我有下面的代码。基本上,如果密钥是这些密钥中的任何一个,我将其推入$ scope.mykey
for (var i = 0; i < response.data.length; i++) {
var allKeys = Object.keys(response.data[i])
for (var k = 0; k < allKeys.length; k++) {
if (allKeys[k] == "ABC" ||
allKeys[k] == "EFG" ||
allKeys[k] == "HIG" ||
allKeys[k] == "KAY" ||
allKeys[k] == "LOP" ||
allKeys[k] == "LLP" ||
allKeys[k] == "JYP" ||
allKeys[k] == "TWC" ||
allKeys[k] == "ZHG" ||
allKeys[k] == "LMD" ||
allKeys[k] == "PKL" ||
allKeys[k] == "JIB" ||
allKeys[k] == "MHT") {
$scope.mykey.push({
name: allKeys[k],
checked: response.data[i].allKeys[k]
});
}
}
但是,我得到了错误
"Cannot read property '7' of undefined
我认为这与
name:
和checked:
有关。例如,应该是这样的:response.data[i].TWC
但是现在我认为它越来越像:
response.data[i].allKeys[7]
有人知道我该怎么做吗?
最佳答案
因为response.data[i]
没有属性allKeys
,您会收到此错误。如果要使用存储在allKeys[k]
中的键作为字符串访问属性,请使用:
response.data[i][allKeys[k]]
附带说明,我建议使用
forEach
循环来提高可读性: response.data.forEach(function(data) {
var allKeys = Object.keys(data);
allKeys.forEach(function(key){
if (key == "ABC" || key == "EFG" || /*...*/ ) {
$scope.mykey.push({ name: key, checked: data[key] });
}
});
});