Reputation: 2959
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.
Upvotes: 0
Views: 78
Reputation: 6052
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];
});
Upvotes: 0
Reputation: 963
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.
Upvotes: 4