I'm using a callback to create an object, which I'd like to parse. I'm able to parse the object when the name/value pair I've specified exists, but unable to identify when the name/value pair in my object is undefined.
JSON Object with name/value pair populated:
parseMe([{"item1" : "", "item2" : "", "item3" : [], "item4" : "content goes here"}]);
JSON Object with name/value parsed undefined:
parseMe([{"error" : "Not available"}]);
Parsing logic EX:
var renderR="";
function parseMe(data){
renderR="";
if(data[0].item4!="collapse") renderR=data[0].item4;
//if name/value pair isn't equal to "collapse" render it.
else if(data[0].item4==='undefined'){
document.getElementById('div1').style.display='none';
//if name/value pair is undefined in object hide the div.
}
}
答案 0 :(得分:1)
您应该使用 typeof 来检查未定义的密钥。
function parseMe(data){
renderR="";
if(data[0].item4!="collapse"){
renderR=data[0].item4;
//if name/value pair isn't equal to "collapse" render it.
}else if(typeof data[0].item4==="undefined"){
document.getElementById('div1').style.display='none';
//if name/value pair is undefined in object hide the div.
}
}
答案 1 :(得分:1)
如上面的评论中所述,else if
条件可以更改为typeof(...) === 'undefined'
以使该方法有效。然而,更标准的解决方案是使用hasOwnProperty方法查询对象的键值,例如
} else if (data[0].hasOwnProperty('item4')) {
在尝试通过点符号或方括号访问属性之前,应首先执行此检查。此外,这不会遍历原型链以确定继承的属性,但它将检测直接属于该对象的任何属性,这对于原始对象值和解析逻辑(例如此)应该足够。因此,包含代码重构的最终解决方案可以使用hasOwnProperty
方法,也可以使用in
运算符和switch语句,例如
for (var key in data[0]) {
var value = data[0][key];
switch (key) {
case "item1":
dosomething(value);
break;
case "item2":
dosomethingelse(value);
break;
// etc...
}
}