Reputation: 97
I'm working on pulling data from a json object and then displaying the information on the front end. 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.
On Google Chrome, I get an Uncaught TypeError: Cannot read property "dm" of undefined based on the code below.
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
{
"556520000":{
"lmin":"35",
"dm":[
{
"Width":"147"
},
{
"Depth":"10"
},
{
"Height":"137"
}
],
"lmax":"68",
}
}
Upvotes: 0
Views: 2456
Reputation: 1365
First you have to check SKU is present in the object, if not add a check. 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');
}
Upvotes: 0