Access deep into javascript objects

Access deep into javascript objects
0.0 0

#1

I have a set validation rule that’s being applied to a set of objects. I need to dig deeper into the “contentType”
and should write a validation.

var rules=  {
         p1: {
             required:true,
             pgName:"string", 
             maxLength:5,
             contentType: {main:"string", Id: "string"}

             },
         p2: {
           required:true,
           pgName:"string",
           maxLength:5
             },
         p3: {
           required: true, 
           pgName:"string", 
           maxLength:5,
           contentType: {sub:"string", Id: "string"}

           }
        }

    obj= {
          p1: {
            pgName:"page1",
            contentType: {main:"template obj", Id: "af3323443"}
            },
          p2: {
            pgName:"page2", 
            },
          p3: {pgName:"page3",
              contentType: {main:"template obj2", Id: "af35455"}}
        };

This validation below has access to “key of obj” and “key of rules”.

 I am not able to dig deeper where we get access to the key of rules[key] and the key of obj[key].
for(let key in rules) {

  if(key in obj) {

    if('pgName' in rules[key]){
      if(typeof obj[key].pgName !== rules[key].pgName){
        console.log(key + " pgName" + " Should have 5 characters");
       }
     }
    if('maxLength' in rules[key]){
      if (obj[key].pgName.length <= rules[key].maxLength){
        console.log(key + " pgName" + " Should have 5 characters");
       }
     }

This is what I tried

if('contentType' in rules[key]){
  if(typeof obj[key].contentType !== rules[key].contentType){
   console.log(key + " pgName" + " Should have 5 characters");
  }
 }

#2

This line

Always return false, becasue typeof(obj[key].contentType) is "object" (it’s a string), and rules[key].contentType is an object.

You should go one more level for contentType for both rules and data.

Just what you did for the whole(root) level, do the same thing for contentType
e.g.

if('contentType' in rules[key]){
    for(let inner_key in rules[key]){
        if(rules[key][inner_key] in obj[key]){
            //validation here now, easy.
        }
    }
}