As I've been exploring various code snippets to check for the presence of object keys within arrays, I came across some brilliant examples that have been really helpful...
However, my current dilemma lies in dealing with a JSON response that requires specific key values to access items within an array. Take a look at the "orders" section:
{"Routes": [
{
"route": {
"id": "1daf1f53-80b6-49d6-847a-0ee8b814e784-20180821"
},
"vehicle": {
"id": "1daf1f53-80b6-49d6-847a-0ee8b814e784"
},
"driver": {
"id": "6c2823be-374e-49e5-9d99-2c3f586fc093"
},
"orders": {
"6df85e5f-c8bc-4290-a544-03d7895526b9": {
"id": "6df85e5f-c8bc-4290-a544-03d7895526b9",
"delivery": {
"customFields": {
"custom": "5379"
}
},
"isService": true
}
}
}
]
};
The code logic functions perfectly until it reaches the point where a specific key value needs to be provided:
function checkProperty(obj, prop) {
var parts = prop.split('.');
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (obj !== null && typeof obj === "object" && part in obj) {
obj = obj[part];
} else {
return false;
}
return true;
}
Below are some test scenarios showcasing both successful and unsuccessful outcomes:
console.log(checkProperty(test, 'Routes.0.orders')); //Valid - returns true
console.log(checkProperty(test, 'Routes.0.orders.id')); //Invalid - returns false
console.log(checkProperty(test, 'Routes.0.orders.6df85e5f-c8bc-4290-a544-03d7895526b9.id)); //Invalid - returns false
I seem to be stuck and any assistance would be greatly appreciated...