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'
Dan
  • 55,715
  • 40
  • 116
  • 154
  • By the Title of the question, maybe a question https://stackoverflow.com/questions/5873624/parse-json-string-into-a-particular-object-prototype-in-javascript will be useful. – Michael Freidgeim Apr 18 '20 at 02:27

2 Answers2

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

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    could you please explain your last sentence better? – Dan Apr 14 '11 at 12:31
  • 2
    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. – ThiefMaster Apr 14 '11 at 12:35
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
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288