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.
CodePudding user response:
you can just insert a ? between the property name and the period between the next property.
var ba = vsp?.specs?.[4]?.value;
also you can use the Nullish coalescing operator :
CodePudding user response:
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.
This operator can be helpful in your use case.
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
.
CodePudding user response:
in the json2 it´s imposible to get vsp.specs[4] because only have positions from 0 to 3 in the array, could ask for the position in the array exists something like
var ba = (4<vsp.length) ? vsp.specs[4].value:null;
or var ba = vsp?.specs?.[4]?.value;
CodePudding user response:
What about check length of array before access it ? As I understand It sound like you try to access item at index 4 which was not there since beginning
sample code to check array length from your 2nd sample
var json = {
"specs": [
{
"value": "info1"
},
{
"value": "info2"
},
{
"value": "info3"
},
{
"value": "infp4"
}
]};
console.log(Object.keys(json['specs']).length); // 4