Lodash - Check for empty array in an array of objects using _.some

我是研究僧i 提交于 2020-01-05 04:00:13

问题


I have an array of objects like this - say testArray. I need to check that for each object in array, if any of the saveNumbers array is empty, my function should return false.

My function is as follows:

  public checkSaveNumbers(): boolean {
    let result;
    if (this.testArray) {
      result = _.some(this.testArray, member => !member.saveNumbers.length);
    }
    console.log(result);
  }

Here, result is showing true for my above object where we can see that the first element in the array has saveNumbers array empty. I'd expect result to be false in that case. I want to achieve this using Lodash and I'm not sure what is going wrong here.

Update:

As suggested in comments, I changed the code to following:

public checkSaveNumbers(): boolean {
  let result = true;
  if (this.testArray) {
    result = _.every(this.testArray, member => member.saveNumbers.length > 0); //as soon as the condition is false, result should become false otherwise result will remain true.
    console.log(result);
  }
}

However, with this code, even when my saveNumbers array is non-empty for every member in testArray, I get result as false.


回答1:


You can rewrite your function as follow:

function checkSaveNumber(testArray) {
    return !_.some(_.map(testArray, 'saveNumbers'), ['length', 0]);  
}

http://jsbin.com/domitexazo/edit?js,console




回答2:


If any of the saveNumbers array is empty, my function should return false.

You tried:

_.some(array, member => !member.saveNumbers.length)

But this means "true if at least one member has empty saveNumbers." Which is exactly the opposite of what you want.

So negate the entire expression.

!_.some(array, member => !member.saveNumbers.length)

UPDATE:

If this is also not working for you:

_.every(array, member => member.saveNumbers.length > 0)

then you have a bug somewhere else.




回答3:


another variant

!_.chain(testArray)
    .map('saveNumbers')
    .map(_.isEmpty)
    .some()
    .value()


来源:https://stackoverflow.com/questions/40919202/lodash-check-for-empty-array-in-an-array-of-objects-using-some

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!