在对象内动态执行功能

时间:2019-01-21 04:11:46

标签: javascript object lodash

我有一个像这样的对象结构:

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

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

我正在尝试通过创建一个具有函数作为值的对象来验证值,当且仅当它们存在时。所以我首先想到的是:

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

这有可能实现吗?

2 个答案:

答案 0 :(得分:2)

您应该只分配功能名称;只需说出book: validateBook(),您就会立即调用它。因此,如下更改functionObj:

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

此外,也不需要单独的数组,一旦验证了v,而不是将其压入数组,只需调用以下相关函数

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

答案 1 :(得分:1)

没有破折号,您可以使用常规ECMAScript功能。下面的代码看起来很多,因为对于未发布的代码,它具有最少的填充。另外,它使用明智的变量名。

运行验证仅需一条线:

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}`);