'Compare two array of objects in Joi
Is there a way to verify that the key that exists in one object is the same as the key that exists in the other object?
For eg:
{
"localizationName": "en-US",
"dataText": [
{
"persona": "gw_user",
"verbiage": "read all patient info gw_user"
},
{
"persona": "patient",
"verbiage": "read all patient info patient"
}
],
"purposeText": [
{
"persona": "gw_user",
"verbiage": "read all patient data <<purspose>> gw_user"
},
{
"persona": "patient",
"verbiage": "read all patient data <<purspose>> patient"
}
]
}
As per the above example, the same personas exist in both "dataText" & "purposeText".
I want a joi validation code for 'whatever personas exist in the "dataText", the same personas should be defined in the "purposeText" as well'.
Below is the joi validation code I could come up with. But that doesn't seem to work.
localizationName: Joi.string()
.valid(...BCP47LanguageTags)
.required()
.messages({ 'any.only': '"localizationName" must be a BCP47 compliant language tag like "en-US"' }),
dataText: Joi.array().items(
Joi.object().keys({
persona: Joi.string().valid(...Persona).required(),
verbiage: Joi.string()
})
).required(),
purposeText: Joi.array().items(
Joi.object().keys({
persona: Joi.string().valid(Joi.in('dataText')).required(),
verbiage: Joi.string()
})
).required()
Any help would be appreciated.
Solution 1:[1]
I've created a function that can be used to compare properties within specified keys of a chosen object. I have also made assumptions that the properties you want to compare will be in the same order within the 2 keys.
See my code below:
var obj = {
"localizationName": "en-US",
"dataText": [
{
"persona": "gw_user",
"verbiage": "read all patient info gw_user"
},
{
"persona": "patient",
"verbiage": "read all patient info patient"
},
{
"persona": "test1",
"verbiage": "added this test"
}
],
"purposeText": [
{
"persona": "gw_user",
"verbiage": "read all patient data <<purspose>> gw_user"
},
{
"persona": "patient",
"verbiage": "read all patient data <<purspose>> patient"
},
{
"persona": "test2",
"verbiage": "added this test"
}
]
};
function CheckPropertiesMatch(obj, keys, property){
for (var i = 0; i < obj[keys[0]].length; i++){
if (obj[keys[0]][i][property] == obj[keys[1]][i][property]){
console.log("Properties at index " + i + " match!");
} else {
console.log("Mismatch at index " + i + "!")
}
}
}
CheckPropertiesMatch(obj, ['dataText',"purposeText"], "persona")
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 | DharmanBot |
