0

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.

1
  • fixed your grammar,works now Commented Feb 16, 2018 at 5:09

2 Answers 2

1

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.