[英]Uncaught TypeError: Cannot read property of undefined JSON
I'm working on pulling data from a json object and then displaying the information on the front end.我正在从 json object 中提取数据,然后在前端显示信息。 What is the best way to wrap the code below to check to see if the variable SKU is undefined or unavailable then to not run the code at all.
包装下面的代码以检查变量 SKU 是否未定义或不可用的最佳方法是什么,然后根本不运行代码。
On Google Chrome, I get an Uncaught TypeError: Cannot read property "dm" of undefined based on the code below.在 Google Chrome 上,我收到 Uncaught TypeError: Cannot read property "dm" of undefined 根据下面的代码。
var SKU = "556520000";
var dimBreak = obj[SKU]["dm"];
for(var i = 0; i < dimBreak.length; i++){
const dimAll = dimBreak[i];
let entries = Object.entries(dimAll);
for(const [prop, val] of entries) {
console.log(prop, val);
}
}
Thanks for your help.谢谢你的帮助。
Based on a comment below根据下面的评论
I've tried below which gives same error as above.我在下面尝试过,它给出了与上面相同的错误。
var dimBreak = obj[SKU]["dm"];
console.log(dimBreak);
if(typeof dimBreak === 'undefined') {
console.log("Is undefined");
} else {
console.log("Is defined");
}
This code below however runs然而,下面的这段代码运行
var dimBreak = "Test";
console.log(dimBreak);
if(typeof dimBreak === 'undefined') {
console.log("Is undefined");
} else {
console.log("Is defined");
}
Object that is used使用的 Object
{
"556520000":{
"lmin":"35",
"dm":[
{
"Width":"147"
},
{
"Depth":"10"
},
{
"Height":"137"
}
],
"lmax":"68",
}
}
First you have to check SKU is present in the object, if not add a check.首先您必须检查 object 中是否存在 SKU,如果没有添加检查。 Your code seems to be working(You can see below)
您的代码似乎正在运行(您可以在下面看到)
var obj = { "556520000":{ "lmin":"35", "dm":[ { "Width":"147" }, { "Depth":"10" }, { "Height":"137" } ], "lmax":"68", } } var SKU = "556520000"; if(obj[SKU]){ var dimBreak = obj[SKU]["dm"]; for(var i = 0; i < dimBreak.length; i++){ const dimAll = dimBreak[i]; let entries = Object.entries(dimAll); for(const [prop, val] of entries) { console.log(prop, val); } } } else { console.log(SKU+' is not defined'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.