0

The code is as follows

const {
      aForm,
      bForm,
      eForm,
      qForm,
    } = this.form;

return (
      aForm.isEditing ||
      bForm.isEditing ||
      eForm.isEditing ||
      qForm.isEditing
    );

Is there a way to refactor this? Something like

const forms = pick(this.form, [
      "aForm",
      "bForm",
      "eForm",
      "qForm",
    ]);
Object.values(forms).map(f => f.isEditing).join("||") //Need to return boolean value.
prajeesh
  • 2,202
  • 6
  • 34
  • 59
  • 1
    Don't know what `pick` is supposed to be, but if `forms` is some sort of dictionary, where the values are objects with an `isEditing` property, `Object.values(forms).every(x => x.isEditing)` should do what you want. [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) – derpirscher Jun 12 '23 at 12:28
  • 1
    pick is used from lodash https://www.geeksforgeeks.org/lodash-_-pick-method/ – prajeesh Jun 12 '23 at 12:33
  • 1
    Oh, that should of course be `Array.some` not `Array.every` ... – derpirscher Jun 12 '23 at 12:42

2 Answers2

5

I think you already have something close to what we (other viewers) would imagine. Here I'd suggest to use Array#some to achieve this. It allows you to check if one of the items matches the condition (a logical OR ||).

You have the opposite function which checks every value (so a logical AND &&).

const properties = [
  "aForm",
  "bForm",
  "eForm",
  "qForm",
]

return properties.some(prop => {
  const obj = this.form[prop] // Get your form item

  return obj.isEditing;
})
nook
  • 1,729
  • 1
  • 12
  • 34
-1
const forms = [
  "aForm",
  "bForm",
  "eForm",
  "qForm",
];
const o = Object.values(forms).map(f => eval(f).isEditing).join("||")
eval(o)
Taron Qalashyan
  • 660
  • 4
  • 8
  • 3
    Consider not encouraging the use of `eval`. (I am not the asker) – evolutionxbox Jun 12 '23 at 12:40
  • It's your approach. – Taron Qalashyan Jun 12 '23 at 12:42
  • 1
    It's true that it's what the OP was trying to do, but the `eval` approach isn't ever a great one. See the other answer. – General Grievance Jun 12 '23 at 13:10
  • In my answers, I'm trying to do minimal changes in the approach of the question owner. Maybe I'm wrong but I think it's more helpful than suggest a solution from scratch. – Taron Qalashyan Jun 12 '23 at 13:15
  • 1
    In principle it may be ok, to solve an issue based on OP's code. But if the original approachs seems to lead to problematic or even dangerous situtations, is better to clarify that and not suggest things like `eval` https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – derpirscher Jun 12 '23 at 15:43
  • Evidently, the other answer was more helpful. Why? Because it suggests a simple alternative and explains itself clearly. – General Grievance Jun 12 '23 at 16:22