How to define many properties of a class from an object with the same property names?

advertisements

I'm working in JS and I've got the following object with a lot of properties:

var foo = {
    prop1: 123,
    prop2: 456,
    prop3: 789,
    ...
    propX: 321
}

I want to set a class with exactly the same properties.

I can do it like that:

this.prop1 = foo.prop1
this.prop2 = foo.prop2
this.prop2 = foo.prop2
...
this.propX = foo.propX

But I'm looking for something like:

for(var property in foo) {
    this.[property] = foo[property]
}

Do you know if it's possible to get this kind of behavior in JS?

I'd like to set my class properties with a single loop for.


Check if this has property and then assign from foo

for(var property in foo) {
    if(this.hasOwnProperty(property)) {
        this[property] = foo[property];
    }
}

or a better way is to loop all keys in this and you do not need if statement.