简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM