How to set a lot a class properties from an object with the same property names?

76 views Asked by At

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.

2

There are 2 answers

0
Jozef Dúc On BEST ANSWER

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.

0
TaoPR On

Iterate through source object property keys and copy values to target objects like this:

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

// Copy properties across
var target = {};
var keys = Object.keys(foo);
keys.forEach(function(key){
    target[key] = foo[key];
});