0

My goal is to create array of objects which have set default properties, but in some cases I will need to update one or more of property. Here is my example class with variables - objects

export class Components{
    public static component_1 = {
        width: 1,
        height: 2,
        x: 3,
        y:4
    }
    
    public static component_2 = {
        width: 10,
        height: 20,
        x: 30,
        y:40
    }

    ...
}

I would like to create my array of object in way eg

let myArrOfComponents = [Components.component_1, Components.component_2, ...]

The problem is that in some cases I will have to update one or more of properties in object, eg width and x. I would like to do this for example like

let myArrOfComponents = [Components.component_1.configure(width = 99, x=88)]

Can you help me how I can do this? Im not sure how implement '.configure()' I'm trying to solve this but have no idea how implement it or something with similar behavior

ciupakabrans
  • 45
  • 1
  • 2
  • 7
  • https://stackoverflow.com/questions/6439915/how-to-set-a-javascript-object-values-dynamically – Robert May 23 '21 at 12:56
  • [Do not use `class` syntax for only `static` members!](https://stackoverflow.com/q/29893591/1048572) – Bergi May 23 '21 at 12:57
  • `{...components.component_1, width: 99, x: 88}` should do. If those are actually instances, you can give them a method to clone+update them, including doing more advanced stuff. Pass an object as the argument, JS does not have named arguments. – Bergi May 23 '21 at 12:59

1 Answers1

0

The simplest option would be to make them methods (so called "factory methods").

class Components {
    static component_1 = (options = null) => ({
        width: 1,
        height: 2,
        x: 3,
        y: 4,
        ...options
    })
}

Now, Components.component_1() will return a default object, and e.g. Components.component_1({x: 25, width: 100}) a "configured" one.

georg
  • 211,518
  • 52
  • 313
  • 390