Search code examples
javascriptecmascript-6lodashis-empty

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


The purpose of function is to get false when all answers are empty. Currently, some how getting **false when only one single answers empty and rest have data inside.

what is the best way to check all answers are empty or not. It doesn't matter some has data and some doesn't. I just wanna see all empty or not.

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/[email protected]/lodash.min.js"></script>


Solution

  • You could use .some(), you will get true if at least 1 answers is not empty, and you will get false if all answers are empty

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