如何检查每个数组对象 属性 是否为空?

How to check any every array object property empty or not?

函数的目的是在所有answers为空的情况下得到false。目前,一些如何在只有一个 answers 为空而其余的内部有数据时得到 **false。

检查所有 answers 是否为空的最佳方法是什么。一些有数据,一些没有,这并不重要。我就想看看全空不空

const questions = [{
    "answers": [{
        "value": "Browns",
        "selected": false,
      },
      {
        "value": "Oranges",
        "selected": false,
      },
      {
        "value": "Purples",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:28.359"
  },
  {
    "answers": [],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:35.392"
  },
  {
    "answers": [{
        "value": "AnimalPrints",
        "selected": false,
      },
      {
        "value": "BigLogos",
        "selected": true,
      },
      {
        "value": "Floral",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:43.883"
  }
];

console.clear();
console.log("------------ES6------------");
const es6Result = questions.every((item) => !_.isEmpty(item.answers));
console.log(es6Result);

const lodashResult = _.every(questions, !_.isEmpty('answers'));
console.log("------------Lodash------------");
console.log(lodashResult);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

我认为你描述的逻辑需要:

const lodashResult = !_.every(questions, _.isEmpty('answers'));

const es6Result = !questions.every((item) => _.isEmpty(item.answers));

你可以使用.some(),如果至少有1个answers不为空,你会得到true,如果所有answers,你会得到false ] 为空

const es6Result = questions.some((item) => item.answers.length);

const questions = [{
    "answers": [{
        "value": "Browns",
        "selected": false,
      },
      {
        "value": "Oranges",
        "selected": false,
      },
      {
        "value": "Purples",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:28.359"
  },
  {
    "answers": [],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:35.392"
  },
  {
    "answers": [{
        "value": "AnimalPrints",
        "selected": false,
      },
      {
        "value": "BigLogos",
        "selected": true,
      },
      {
        "value": "Floral",
        "selected": false,
      }
    ],
    "info": "",
    "type": "DESELECT",
    "lastUpdated": "2021-11-01T22:50:43.883"
  }
];

console.clear();
console.log("------------ES6------------");
const es6Result = questions.map((item) => _.isEmpty(item.answers)).indexOf(true) > -1;
console.log(es6Result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

这里真的不需要lodash。你应该能够通过使用 Array.prototype.every

来完成你想要的
questions.every((item) => item.answers.length > 0)

这将始终 return 为真,只要所有 'answers' 数组中都包含一项或多项,否则为假。 作为 said, you can use Array.prototype.some 当您想要检查至少一项时。