0

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?

2
  • 1
    "…validate the values, if and only if they exist". A property with a value of "" (empty string) exists. I'd suggest validating each property and have the validation function do all the validation. It's quite possible to do what you want, you don't need lowdash to do it. Commented Jan 21, 2019 at 4:21
  • 1
    see the @Gowri's answer, invoke function will return it's return value and assign it to the property, Commented Jan 21, 2019 at 4:26

2 Answers 2

2

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]();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.