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..
JavaScript
x
6
1
if (file.xhr.response) {
2
console.log(Exists);
3
} else {
4
console.log(Missing);
5
}
6
This works when file.xhr.response exists but if it doesn’t then it throws an error…
JavaScript
1
2
1
Uncaught TypeError: Cannot read property 'response' of undefined
2
Where am I going wrong?
Advertisement
Answer
You can check if object property exists using:
JavaScript
1
4
1
if (file && file.xhr && file.xhr.response) {
2
// your logic...
3
}
4
Code:
JavaScript
1
11
11
1
const a = {
2
b: {
3
d: 'd'
4
}
5
}
6
7
const resultC = a && a.b && a.b.c ? 'Exists' : 'Missing';
8
console.log('a.b.c', resultC);
9
10
const resultD = a && a.b && a.b.d ? 'Exists' : 'Missing';
11
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:
JavaScript
1
29
29
1
const a = {
2
b: {
3
d: {
4
d: {
5
e: {
6
f1: {
7
g: {
8
h: 'h',
9
}
10
},
11
f2: {
12
g: {
13
h: {
14
i: 'i',
15
},
16
},
17
},
18
},
19
},
20
},
21
},
22
}
23
24
const checkObjectProp = (o, p) => Object
25
.keys(o)
26
.some(k => k === p || (typeof o[k] === 'object' && checkObjectProp(o[k], p)))
27
28
const resultI = checkObjectProp(a, 'i') ? 'Exists' : 'Missing'
29
console.log(resultI)