2

I want to do the following

var my_json = {
    a : 'lemon',
    b : 1
}

function obj(json){
    this.a = 'apple';
    this.b = 0;
    this.c = 'other default';
}

after assigning

var instance = obj(my_json)

I want to get

instance.a == 'lemon'
1

2 Answers 2

7
for(var key in json) {
    if(json.hasOwnProperty(key)) {
        this[key] = json[key];
    }
}

The if block is optional if you know for sure that nothing is every going to extend Object.prototype (which is a bad thing anyway).

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

2 Comments

could you please explain your last sentence better?
If you extend Object.prototype, iterating over objects will include the properties you added to the prototype which is most likely not what you want when iterating over an object coming from JSON. If a property comes from the prototype, the hasOwnProperty check will fail so it will prevent breakage as only the properties which are actually in the passed objects will be copied to your object.
2

If you want defaults how about;

function obj(json){
  var defaults = {
    a: 'apple',
    b: 0,
    c: 'other default'
  }

  for (var k in json)
    if (json.hasOwnProperty(k))
      defaults[k] = json[k];

  return defaults
}

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.