Determining if all attributes on a javascript object are null or an empty string

后端 未结 15 1817
走了就别回头了
走了就别回头了 2020-12-08 04:08

What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string? It should work for an arbitrary number of attributes

15条回答
  •  我在风中等你
    2020-12-08 04:40

    This skip the function attribute

    function checkIsNull(obj){
    		let isNull=true;
    		for(let key in obj){
    			if (obj[key] && typeof obj[key] !== 'function') {
    				isNull = false;
    			}
    		}
    		return isNull;
    	}
    
    var objectWithFunctionEmpty={
      "name":undefined,
      "surname":null,
      "fun": function (){ alert('ciao'); }
    }
    
    var objectWithFunctionFull={
      "name":undefined,
      "surname":"bla bla",
      "fun": function (){ alert('ciao'); }
    }
    
    checkIsNull(objectWithFunctionEmpty); //true
    checkIsNull(objectWithFunctionFull); //false

提交回复
热议问题