0

I have an array like below.

let report = [
  {0: { error1: '', error2: ''}},
  {1: { error1: '', error2: ''}}
]

I want to check if all the error values are empty. Then based on that result I will enable or disable a button. If all the error values are empty, then the save button will be enabled. How can I achieve that ?

2
  • 1
    What have you tried so far? Commented Jan 27, 2021 at 10:57
  • Check it's syntax report, haven't found anything useful. Commented Jan 27, 2021 at 11:00

2 Answers 2

1

See this:

let report = [
  { 0: { error1: "", error2: "" } },
  { 1: { error1: "", error2: "" } },
];

const testToSeeAllErrorsAreEmpty = report.every((item) =>
  Object.values(item).every((objContainsErrors) =>
    Object.values(objContainsErrors).every((error) => !error)
  )
);

console.log("testToSeeAllErrorsAreEmpty: ", testToSeeAllErrorsAreEmpty)

Sign up to request clarification or add additional context in comments.

Comments

0

This recursive function checks if an object (or array) is empty, if not iterates it's properties, and check if they are empty. If the a property is an object (or array), the function checks if it's empty and so on. Only if all leaves are empty, the function returns true.

const checkEmptyLeaves = o => {
  if(_.isObject(o)) return _.isEmpty(o) || _.every(o, checkEmptyLeaves);
  
  return _.isEmpty(o);
};

const report1 = [
  { 0: { error1: "", error2: "" } },
  { 1: { error1: "", error2: "" } },
];

const report2 = [
  { 0: { error1: "", error2: { message: "some message" } } },
  { 1: { error1: "", error2: "" } },
];

console.log(checkEmptyLeaves(report1));
console.log(checkEmptyLeaves(report2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.