-2

Given this object:

var myObject = {name: 'David', date: '11/13/2014'};

I want my constructor to set its object properties based on myObject:

function myClass(_object){
    // set given object's properties here
}

I want to set the properties through a loop, so I wont have to set every property by hand - because the object will be dynamic.

I'm looking for a cross-browser solution.

3
  • this.name = _object.name || "Joe"; Commented Nov 12, 2014 at 22:09
  • Oh, what's your question? Commented Nov 12, 2014 at 22:09
  • @Jonathan this is very obvious, I'm sorry I didn't mention but the object may be dynamic, so I won't set every property. I want some sort of loop to accomplish it. Commented Nov 12, 2014 at 22:10

1 Answer 1

1

Perhaps what you want is this:

function MyClass(_object) {
  for (var p in _object) {
    if (_object.hasOwnProperty(p)) {
      this[p] = _object[p];
    }
  }
}

Don't forget to use new:

var obj = new MyClass(myObject);

Fiddle

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

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.