Dan
Dan

Reputation: 57891

Initialize a JavaScript object using JSON

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'

Upvotes: 2

Views: 16605

Answers (2)

Alex K.
Alex K.

Reputation: 175816

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
}

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318518

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

Upvotes: 7

Related Questions