'How to check for the existence of dynamic property inside an object?
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
const result = {
"MEN": [],
"WOMEN": [],
"CHILDREN TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
I have an object result like above. Sometimes, it may have KIDS TEMP property and sometimes CHILDREN TEMP. Since this property has spaces, I cannot use dot operator to fetch these properties.
I want to create a flag if either of KIDS TEMP or CHILDREN TEMP exist.
I tried below:-
const part = 'KIDS TEMP' || 'CHILDREN TEMP';
let check;
if (result) {
check = !!(result?.MEN.length !== 0 || result[part].length !== 0);
}
But the above code breaks when I receive CHILDREN TEMP saying that it cannot read length of undefined.
How do I fix this?
Solution 1:[1]
Object.keys() returns the property names of an object. You can check like this, if an object possesses a certain property:
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
console.log(Object.keys(result).includes("KIDS TEMP"));
console.log(Object.keys(result).includes("CHILDREN TEMP"));
If you want to test, if a certain attribute exists, and in case it exists, contains a non-empty array, you can test it like this:
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
console.log(result["KIDS TEMP"]?.length > 0);
console.log(result["CHILDREN TEMP"]?.length > 0);
The main problem with your code is that const part = string1 || string2 always evaluates to string1, which is not what you intend to do.
Solution 2:[2]
You can use Object's method hasOwnProperty it will return true/false depends on if property exists in object or not.
const result = {
"MEN": [],
"WOMEN": [],
"KIDS TEMP": [
"BCDEFHJJJJJJ34EEE234",
"ABCDEFGHIJKL12345678"
]
}
console.log(result.hasOwnProperty('KIDS TEMP'),result.hasOwnProperty('CHILDREN TEMP'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | RA17H45M40S |
