简体   繁体   English

如何使用 lodash _isEmpty 检查对象是否为空?

[英]How to check if object is empty using lodash _isEmpty?

i have map function that is returning empty object for the array now if i check array _isEmpty this condition should satisfy but its not getting into if statement.如果我检查数组_isEmpty这个条件应该满足但它没有进入 if 语句,我有 map 函数现在返回数组的空对象。 Any idea what is implemented wrong or better approach ?知道什么是错误的或更好的方法吗?

main.js主文件

const validateResponse = _.map(drugs ,validateValues);

now validateResponse returns [{}] and it should satisfy condition现在 validateResponse 返回 [{}] 并且它应该满足条件

  if (_.isEmpty(validateResponse)) {
      throw invalidPriceError;
    }

As per the lodash documentation here :根据此处的 lodash 文档:

Array-like values such as arguments objects, arrays, buffers, strings, or jQuery-like collections are considered empty if they have a length of 0. Similarly, maps and sets are considered empty if they have a size of 0.类似数组的值,例如参数对象、数组、缓冲区、字符串或类似 jQuery 的集合,如果它们的长度为 0,则被认为是空的。同样,如果 map 和 set 的大小为 0,则它们被认为是空的。

[{}].length happens to be 1. A cabbage-in-a-box, if you will. [{}].length恰好是 1。如果您愿意,可以吃盒装卷心菜。 An array with one empty object.一个包含一个空对象的数组。 Hence, isEmpty evaluates to false.因此, isEmpty 的计算结果为 false。 [].length , on the other hand, equals 0.另一方面, [].length等于 0。

You'll have to compact out the internals or check one level deeper:您必须压缩内部结构或检查更深一层:

if (!validateResponse.filter(r => !_.isEmpty(r)).length){
  throw invalidPriceError;
}

There might be a handful of other cases you want to cover, like empty array, or an array of two empty objects, etc. Variations on the following should do what you need...可能还有一些您想要涵盖的其他情况,例如空数组或包含两个空对象的数组等。以下的变化应该满足您的需要...

 let array = [{}]; // contains any empty object console.log(_.some(array, _.isEmpty)) // contains only empty objects console.log(_.every(array, _.isEmpty)) // contains exactly one empty object console.log(_.every(array, _.isEmpty) && array.length == 1)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>

If you just want to check if there is a single array with a single empty object [{}] you can use _.isEqual :如果您只想检查是否有一个带有单个空对象[{}]数组,您可以使用_.isEqual

 const hasEmpty = arr => _.isEqual(arr, [{}]) console.log(hasEmpty([])) // false console.log(hasEmpty([{}])) // true console.log(hasEmpty([{}, {}])) // false console.log(hasEmpty([{ a: 1 }])) // false
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Since the array isn't actually empty, but what you're truly checking for is "does the array have exactly one value, and is that single value an empty object?", you could just do this check:由于数组实际上不是空的,但您真正要检查的是“数组是否只有一个值,并且该单个值是一个空对象?”,您可以执行以下检查:

if (validateResponse.length === 1 && _.isEmpty(validateResponse[0])) {
      throw invalidPriceError;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM