I have a javascript object called file, I am trying to check if this object has file.xhr.response property contained in it. I have tried like this..
if (file.xhr.response) {
console.log(Exists);
} else {
console.log(Missing);
}
This works when file.xhr.response exists but if it doesn't then it throws an error...
Uncaught TypeError: Cannot read property 'response' of undefined
Where am I going wrong?
You can check if object property exists using:
if (file && file.xhr && file.xhr.response) {
// your logic...
}
Code:
const a = {
b: {
d: 'd'
}
}
const resultC = a && a.b && a.b.c ? 'Exists' : 'Missing';
console.log('a.b.c', resultC);
const resultD = a && a.b && a.b.d ? 'Exists' : 'Missing';
console.log('a.b.d', resultD);
But if you are dealing with a complex/bigger object you can recursively search for the property within the object
Code:
const a = {
b: {
d: {
d: {
e: {
f1: {
g: {
h: 'h',
}
},
f2: {
g: {
h: {
i: 'i',
},
},
},
},
},
},
},
}
const checkObjectProp = (o, p) => Object
.keys(o)
.some(k => k === p || (typeof o[k] === 'object' && checkObjectProp(o[k], p)))
const resultI = checkObjectProp(a, 'i') ? 'Exists' : 'Missing'
console.log(resultI)
Might be a little late to the party, but you can use the optional chaining
operator (?.).
What this operator does, is if the object it is trying to access is null or undefined, it "short circuits" and returns undefined.
You can use it to check if a property exists like this:
if (file?.xhr?.response !== undefined) {
console.log("exists");
} else {
console.log("missing");
}
This operator has been Baseline Widely Available since July 2020, according to MDN.
const myObject = {
theAnswer: 42,
subObj: {
existentProp: 37,
}
}
console.log(myObject?.theAnswer);
console.log(myObject?.subObj?.existentProp);
console.log(myObject?.subObj?.nonExistentProp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With