To initialize an Object array property and then push values seems to be a two step approach. Is there an optimal one line approach in ES6? Example of the issue is in the appendError(prop, error) method below.
Question:
Is there one line or more concise approach with JS or lodash?
Future optional chaining seems solve the problem, but is there a solution today? PHP allows $array[prop][] = val;
class Errors {
constructor(fields ) {
this.errors = {};
}
/**
* Clear one or all error fields.
*
* @param {string} prop | example: "email"
* @param {string} error | example: "Invalid email"
*/
appendError(prop, error) {
/* Set key and empty array if property doest exist */
if (!this.has(prop)) this.errors[prop] = [];
/* then Push value */
this.errors[prop].push(error);
}
/**
* Determine if an errors exists for the given field.
*
* @param {string} prop
*/
has(prop) {
return this.errors.hasOwnProperty(prop);
}
}