Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  41] [ 1]  / answers: 1 / hits: 16186  / 13 Years ago, thu, april 14, 2011, 12:00:00

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'

More From » json

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


[#92730] Wednesday, April 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marint

Total Points: 550
Total Questions: 105
Total Answers: 124

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;