簡體   English   中英

如何檢查 NodeJS 中的 JSON 是否為空?

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

我有一個函數可以檢查請求是否有任何查詢,並根據它執行不同的操作。 目前,我有if(query)做其他事情。 但是,似乎當沒有查詢數據時,我最終得到一個{} JSON 對象。 因此,我需要將if(query)替換為if(query.isEmpty())或類似的東西。 誰能解釋我如何在 NodeJS 中執行此操作? V8 JSON 對象是否具有此類功能?

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

// 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;
}

用法示例:

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

你可以使用這個:

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

或這個:

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

你也可以使用這個:

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

  return true;
}

如果使用下划線jQuery ,您可以使用它們的isEmptyisEmptyObject調用。

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

因為只需要檢查 Object 是否為空,所以直接調用本地方法 Object.keys(myObj).length 會更好,它通過在內部迭代 for..in 循環返回鍵數組。作為Object.hasOwnProperty返回基於對象中存在的屬性的布爾結果,該對象本身使用 for..in 循環進行迭代,時間復雜度為 O(N2)。

另一方面,調用本身具有以上兩個實現或其他實現的 UDF 對於小對象會很好地工作,但會阻塞代碼,如果對象大小很大,將對整體性能產生嚴重影響,除非事件循環中沒有其他等待。

如果您與Object.keys兼容,並且 node 確實具有兼容性,那么您應該肯定會使用它。

但是,如果你沒有兼容性,並且出於任何原因使用循環函數是不可能的 - 像我一樣,我使用了以下解決方案:

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

將此解決方案視為僅在必要時才使用的“最后手段”。

在評論中看到“這個解決方案在很多方面都不理想”。

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

我的解決方案:

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
const isEmpty = (value) => (
    value === undefined ||
    value === null ||
    (typeof value === 'object' && Object.keys(value).length === 0) ||
    (typeof value === 'string' && value.trim().length === 0)
  )

module.exports = isEmpty;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM