PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to check if object is empty in javascript for all levels in object

 October 28, 2022     arrays, is-empty, javascript, json, object     No comments   

Issue

I wanted to find out if my object is empty or not for all its nested objects and key-value pairs.

for e.g.,

const x = {
  a:"",
  b:[],
  c:{
    x:[]
  },
  d:{
    x:{
      y:{
        z:""
      }
    }
  }
};

this should be an empty object and if any of this contains single value then it should be non empty.


Solution

Here is the way to do what using recursion

const x = {
  a:"",
  b:[],
  c:{
    x:[]
  },
  d:{
    x:{
      y:{
        z:''
      }
    }
  }
};
function checkEmpty(obj){
  
  for(let key in obj){
    //if the value is 'object'
    if(obj[key] instanceof Object === true){
      if(checkEmpty(obj[key]) === false) return false;
    }
    //if value is string/number
    else{
      //if array or string have length is not 0.
      if(obj[key].length !== 0) return false;
    }
  }
  return true;
}
console.log(checkEmpty(x))
x.d.x.y.z = 0;
console.log(checkEmpty(x));



Answered By - Maheer Ali
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing