i trying to get some data json from my api, But I faced this problem:
Code javascript to get json data from my API :
// Get Specs
$.getJSON('https://my_api' , function(specs) {
console.log(specs);
$.each(specs, function(index, vsp) {
console.log(vsp);
var in = vsp.specs[0].value;
var ch = vsp.specs[1].value;
var ra = vsp.specs[2].value;
var ca = vsp.specs[3].value;
var ba = vsp.specs[4].value;
JSON data Ex:1 :
"specs": [
{
"value": "info1"
},
{
"value": "info2"
},
{
"value": "info3"
},
{
"value": "infp4"
},
{
"value": "info5"
}
]
JSON data Ex:2 :
"specs": [
{
"value": "info1"
},
{
"value": "info2"
},
{
"value": "info3"
},
{
"value": "infp4"
}
]
For the first example, everything works fine, but for the second example i’m having this problem :
Cannot read properties of undefined (reading 'value')
var ba = vsp.specs[4].value; ==> value is undefined
How i can skip this var if is undefined ?
Any help would appreciate it.
>Solution :
You can use the optional chaining (?.) operator.
According to MDN:
The optional chaining operator (
?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
To use it, simply use the code below.
var ba = vsp.specs[4]?.value;
This will, instead of throwing an error if it can’t find the value property, return undefined.
This should help with the error. However, you should still add a check for if the variable is undefined. You can use something like below.
ba = ba ?? "Fallback";
This will use the left-hand side value (ba) unless it is null or undefined, in which case will use the right-hand side value ("Fallback").
An if statement can do something similar.
if (typeof ba === "undefined" || ba === null) {
ba = "Fallback";
}
The reason you can’t use ! is because it will evaluate anything of a falsy value to be false. This will only fallback if it is undefined or null.
