Search code examples
javascriptobjectlodash

Dynamically execute function within object


I have an object structure like:

const object = {
  book: '',
  publisher: '',
  author: 'Sally',
  year: '2018',
}

const functionObj = {
  book: validateBook(),
  publisher: validatePublisher(),
  author: validateAuthor(),
  year: validateYear(),
}

I am trying to validate the values, if and only if they exist by creating an object with functions as the values. So my first thought is this:

const nonEmptyArray = [];
_.each(object , (v, k) => if (v) nonEmptyAddListingArray.push(k);
console.log(nonEmptyArray); // ['author', 'year']

// Execute each function in the array.
_.each(functionObj, (key) => function.key();

Is this possible to accomplish?


Solution

  • you should just assign the function name; by saying book: validateBook() you would be immediately invoking it. so change the functionObj as below:

    const functionObj = {
      book: validateBook,
      publisher: validatePublisher,
      author: validateAuthor,
      year: validateYear,
    }
    

    Also there need not be a separate array and each, once v is validated instead of pushing to array, just invoke the related function as below

    _.each(object , (v, k) => if (v) functionObj[k]();