Reputation: 55
I was wondering if there is a way to refrence a variable pointer to a property of an object. For example, in the following code:
function foo(){
this.x=0;
this.y=0;
this.bar=0;
}
var attr={x:"100",y:"42"};
var test=new foo();
for(var key in attr){
test.key=attr[key];
}
console.log(test.x);
console.log(text.y);
I would like this program to output 100 and 42 to show that test.x and test.y have been set using the above method that can set any arbitrary property of an object. Is this at all possible? Thanks in advance for the help.
Upvotes: 0
Views: 33
Reputation: 117
Please check this:
function foo(){
this.x=0;
this.y=0;
this.bar=0;
}
var attr={x:"100",y:"42"};
var test=new foo();
for(var key in attr){
test[key] = attr[key];
}
console.log(test.x);
console.log(test.y);
Upvotes: 1
Reputation: 3747
function foo() {
this.x = 0;
this.y = 0;
this.bar = 0;
}
var attr = {
x: 100,
y: 42
};
// Your code:
/*var test = new foo();
for(var key in attr) {
test.key=attr['key'];
}*/
// Using Object.assign()
var test = Object.assign({}, new foo(), attr);
console.log(test.x);
console.log(test.y);
Upvotes: 1