Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

89
Vistas
Suggest how to write this more compact

Many equal properties names in this code. Is it possible to make it a lot compact ?

constructor(product) {
    this.session = SessionBuilder.create();
    this.id = product.id;
    this.name = product.name;
    this.root = product.root;
    this.pics = product.pics;
    this.sizes = product.sizes;
    this.colors = product.colors;
    this.rating = product.rating;
    this.feedbacks = product.feedbacks;
}

I found only one solution with getters.

constructor(product) {
    this.session = SessionBuilder.create();
    this.product = product;
}

get id() {
    return this.product.id;
}

get name() {
    return this.product.name;
}

...

But i don't really like it. It looks better (for me), but code would be a lot more... Can someone suggest a better solution?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could use a table-driven approach to safely copy only a known set of properties without having to name the properties more than once:

const propNames = ["id", "name", "root", "pics", "sizes", "colors", "rating", "feedbacks"];

class Whatever {
    
    constructor(product) {
        this.session = SessionBuilder.create();
        for (let prop of propNames) {
            this[prop] = product[prop];
        }
    }
    ...
}

If you just want to copy all properties from the product variable, you can use Object.assign():

class Whatever {
    
    constructor(product) {
        this.session = SessionBuilder.create();
        Object.assign(this, product);
    }
    ...
}

But, this is less safe as people could put anything in the product object, including things that might even override your own methods or properties besides the once you intended.


You can see solutions using object destructuring assignment here in this question: Is it possible to destructure onto an existing object?, but I didn't see any solutions there that are simpler than these.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda