{
"Body": {
"LeadDetails": {
"HeaderActionCode": "Add",
"ActionCode": "Add",
"Version": 1,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0
}
]
}
]
}
]
}
}
}
I have the above json as request using json schema validation i want to make sure the value of 'ActionCode' should be same as HeaderActionCode for any level of child I can have
CodePudding user response:
We can do it via Breadth-first search iteration
const validate = (value) => {
let data = value.Body.LeadDetails
let actionCode = data.HeaderActionCode
let items = data.LineItems
while(items.length > 0){
let i = items.shift()
if(i.ActionCode !== actionCode){
return false
}
if(i.LineItems){
items.push(...i.LineItems)
}
}
return true
}
console.log(validate(json))
let json =
{
"Body": {
"LeadDetails": {
"HeaderActionCode": "Add",
"ActionCode": "Add",
"Version": 1,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0,
"LineItems": [
{
"ActionCode": "Add",
"Version": 0
}
]
}
]
}
]
}
}
}
const validate = (value) => {
let data = value.Body.LeadDetails
let actionCode = data.HeaderActionCode
if(actionCode !== data.ActionCode){
return false
}
let items = data.LineItems
while(items.length > 0){
let i = items.shift()
if(i.ActionCode !== actionCode){
return false
}
if(i.LineItems){
items.push(...i.LineItems)
}
}
return true
}
console.log(validate(json))
CodePudding user response:
This one is using a recursion and an unusual use of throwing Error in order to break early if we find an invalid item or sub-item. This is actually DFS (Depth First Search).
var obj = {Body:{LeadDetails:{HeaderActionCode:"Add",ActionCode:"Add",Version:1,LineItems:[{ActionCode:"Add",Version:0,LineItems:[{ActionCode:"Add",Version:0,LineItems:[{ActionCode:"Add",Version:0}]}]}]}}};
function inspectLineItems(arr, HeaderActionCode) {
if (!arr) return true;
arr.forEach(function(item) {
if (item.ActionCode != HeaderActionCode || !inspectLineItems(item.LineItems, HeaderActionCode)) {
throw new Error("missmatch")
}
})
return true;
}
function inspectLeadDetails(obj) {
try {
var HeaderActionCode = obj.HeaderActionCode;
return inspectLineItems(obj.LineItems, HeaderActionCode);
} catch (ex) {
return false
}
}
console.log(inspectLeadDetails(obj.Body.LeadDetails))