Jghorton14
Jghorton14

Reputation: 754

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?

Upvotes: 0

Views: 58

Answers (2)

RobG
RobG

Reputation: 147363

Without lowdash, you can use stock ECMAScript features. The following looks a lot of code because it has minimal polyfills for the code you didn't post. Also, it uses sensible variable names.

Running the validation is a one liner:

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


// And define the validation function in the validation object:
let functionObj = {
  book: function(){
    return this.book === '' || this.book.length > 1;
  },
  publisher: function(){
    return this.publisher === '' || this.publisher.length > 1;
  },
  author: function(){
    return this.author === '' || this.author.length > 1;
  },
  year: function() {
    return this.year === '' || this.year > 1900;
  }
}

// Run the validation
let isValid = Object.keys(object).every(key => functionObj[key].call(object));

// which, if minification matters, could be:
// Object.keys(o).every(k => f[k].call(o));

console.log(`Is valid? ${isValid}`);

Upvotes: 1

Gowri
Gowri

Reputation: 394

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]();

Upvotes: 2

Related Questions