[英]Validate the JSON object availablity in javascript
Inside the json object I traverse upto 4 level something any of the level may undefined and code break. 在json对象内部,我遍历了4个级别,其中任何级别都可能未定义并且代码中断。
How validate/check json node in JavaScript not in jquery 如何在JavaScript中而不是jQuery中验证/检查JSON节点
productDetail.breadcrumb.levels.push(paramObj.categories.category.category.category.CATEGORYNAME);
You need to check it like this : 您需要像这样检查它:
var categoryName = (paramObj.categories
&& paramObj.categories.category
&& paramObj.categories.category.category
&& paramObj.categories.category.category.CATEGORYNAME);
This will give you the category name or undefined if any of the objects along the way are not there. 如果沿途的任何对象都不存在,这将为您提供类别名称或未定义的名称。
Abstract it out into a checking function 将其抽象为检查功能
function myJsonValue(ob, prop) {
var propsArray = prop.split('.');
var out = ob;
var i;
for (i=0; i < propsArray.length; i += 1){
var dis = propsArray[i];
if (!out[dis]) {
return undefined;
}
out = out[dis];
}
return out;
}
Usage: 用法:
myJsonValue(paramObj, "categories.category.category.category.CATEGORYNAME")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.