0

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
  • 2
    Use this[property] instead. Commented Jun 10, 2015 at 15:57
  • @m4ktub I can't believe it was so easy... Commented Jun 10, 2015 at 16:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.