Javascript 如何检查 NodeJS 中的 JSON 是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11480769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:00:08  来源:igfitidea点击:

How can I check if a JSON is empty in NodeJS?

javascriptjsonnode.jsv8

提问by thisissami

I have a function that checks to see whether or not a request has any queries, and does different actions based off that. Currently, I have if(query)do this else something else. However, it seems that when there is no query data, I end up with a {}JSON object. As such, I need to replace if(query)with if(query.isEmpty())or something of that sort. Can anybody explain how I could go about doing this in NodeJS? Does the V8 JSON object have any functionality of this sort?

我有一个函数来检查请求是否有任何查询,并根据它执行不同的操作。目前,我已经if(query)做了其他事情。但是,似乎没有查询数据时,我最终得到了一个{}JSON 对象。因此,我需要替换if(query)if(query.isEmpty())或类似的东西。有人能解释一下我如何在 NodeJS 中做到这一点吗?V8 JSON 对象是否具有此类功能?

回答by PleaseStand

You can use either of these functions:

您可以使用以下任一功能:

// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}

Example usage:

用法示例:

if (isEmptyObject(query)) {
  // There are no queries.
} else {
  // There is at least one query,
  // or at least the query object is not empty.
}

回答by ali haider

You can use this:

你可以使用这个:

var isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
}

or this:

或这个:

function isEmpty(obj) {
  return !Object.keys(obj).length > 0;
}

You can also use this:

你也可以使用这个:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
      return false;
  }

  return true;
}

If using underscoreor jQuery, you can use their isEmptyor isEmptyObjectcalls.

如果使用下划线jQuery,您可以使用它们的isEmptyisEmptyObject调用。

回答by Shubham Sharma

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnPropertyreturns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

由于只需要检查 Object 是否为空,因此最好直接调用本机方法 Object.keys(myObj).length,该方法通过使用 for..in 循环内部迭代Object.hasOwnProperty返回键数组。As返回布尔结果基于对象中存在的属性,该对象本身使用 for..in 循环进行迭代,时间复杂度为 O(N2)。

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

另一方面,调用本身具有以上两种实现或其他实现的 UDF 将适用于小对象,但会阻塞代码,如果对象大小很大,除非事件循环中没有其他任何东西在等待,否则这将对整体性能产生严重影响。

回答by guy mograbi

If you have compatibility with Object.keys, and node does have compatibility, you should use that for sure.

如果您与 兼容Object.keys,并且 node 确实具有兼容性,那么您肯定应该使用它。

However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:

但是,如果您没有兼容性,并且出于任何原因使用循环函数是不可能的 - 像我一样,我使用了以下解决方案:

JSON.stringify(obj) === '{}'

Consider this solution a 'last resort' use only if must.

仅在必须时才将此解决方案视为“最后的手段”。

See in the comments "there are many ways in which this solution is not ideal".

请参阅评论“此解决方案在很多方面都不理想”。

I had a last resort scenario, and it worked perfectly.

我有一个不得已的方案,而且效果很好。

回答by Trung Nguyên

My solution:

我的解决方案:

let isEmpty = (val) => {
    let typeOfVal = typeof val;
    switch(typeOfVal){
        case 'object':
            return (val.length == 0) || !Object.keys(val).length;
            break;
        case 'string':
            let str = val.trim();
            return str == '' || str == undefined;
            break;
        case 'number':
            return val == '';
            break;
        default:
            return val == '' || val == undefined;
    }
};
console.log(isEmpty([1,2,4,5])); // false
console.log(isEmpty({id: 1, name: "Trung",age: 29})); // false
console.log(isEmpty('TrunvNV')); // false
console.log(isEmpty(8)); // false
console.log(isEmpty('')); // true
console.log(isEmpty('   ')); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true