Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
JS Object array property initializer / optional chaining

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);
    }
  }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Logical nullish assignment (??=) to assign an empty array, if the property value id undefined:

(this.errors[prop] ??= []).push(error);

Example:

class Errors {
  constructor(fields) {
    this.errors = {};
  }

  appendError(prop, error) {
    (this.errors[prop] ??= []).push(error);
  }
}

const errors = new Errors;

errors.appendError('a', 'a');

errors.appendError('a', 'b');

console.log(errors.errors);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could abuse || for that:

this.errors[prop]?.push(error) || (this.errors[prop] = [error]);
about 4 years ago · Juan Pablo Isaza Relatório

0

You could write something like:

appendError(prop, error) {
    (this.error[prop] = this.error[prop]||[]) && this.error[prop].push(error) && this.error[prop];
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda