Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!