I'm trying to figure out how to "ignore" TypeErrors during a For Loop, but I would like to pass an empty string value to my variable when I do come across a TypeError or a property that does not exist. I have tried some try/catch with TypeError, but I'm not quite sure what to do with the catch. Any help is appreciated...
My obj
theObj = [
{
name:"Billy",
age:"30",
level:"10"
},
{
name:"Jimbo",
age:"25",
level:"8"
},
{
name:"Ralph",
age:"37"
},
{
name:"Rita",
age:"23",
level:"3"
}
]
Loop
for (var i = 0; i < theObj.length; i ) {
const levels = theObj[i]['level']
console.log(levels)
}
console
10
8
undefined
3
What I would like to see
10
8
3
OR
10
8
Null or some other value like DNE, N/A
3
CodePudding user response:
No problem
for (var i = 0; i < theObj.length; i ) {
const levels = theObj[i]['level']
console.log(levels ? levels : "")
}
CodePudding user response:
Try theObj[i]?.level
, like:
const theObj = [
{
name:"Billy",
age:"30",
level:"10"
},
{
name:"Jimbo",
age:"25",
level:"8"
},
{
name:"Ralph",
age:"37"
},
{
name:"Rita",
age:"23",
level:"3"
}
];
for (let i = 0; i < theObj.length; i ) {
const levels = theObj[i]?.level;
console.log(levels)
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
you should try this
const levels = theObj?.[i]?.['level'] || ""
?. make sure that the parent is defined and if not it will return undefined