[SOLVED] Array of functions with condition

Issue

I am currently working on an array of functions and want to get the right function back with a condition.

Here is my code :

  {'key':'a', 'function':func_a},
  {'key':'b', 'function':func_b},
  {'key':'c', 'function':func_c},
  {'key':'d', 'function':func_d}
];

const term = 'b';

const funcToDo = for (var i = 0; i < array.length; i++) {
    if (term === a[i].key) {
      return a[i].function
    }
  }

const shouldIDoIt = true;
shouldIDoIt === true ? functToDo() : null;

Can someone help me on this ?

Solution

Use Array.prototype.find to then return from that array an Object which matches a specific property value

const find = (arr, k, v) => arr.find(ob => ob[k] === v);

const func_a = () => console.log("aaa!");
const func_b = () => console.log("bbb!");
const func_c = () => console.log("ccc!");

const arrFn = [
  {key: "a", function: func_a},
  {key: "b", function: func_b},
  {key: "c", function: func_c},
];

const funcToDo = find(arrFn, "key", "b")?.function;
const shouldIDoIt = true;

funcToDo && shouldIDoIt && funcToDo();

Answered By – Roko C. Buljan

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *