JSON with existing Objects

R

routeslip

Hi. I'm pretty experienced with Javscript but totally new to JSON and
have a question...

Is it possible to use JSON to "populate" objects that are already
defined? For instance, I have two "classes":

function class1() {
this.class2_array;
}

function class2() {
this.prop1;
this.prop2;
this.prop3;
this.prop4;
}

I want to create a bunch of class2 objects in the class1.class2_array
property.

The existing classes already have their own methods, etc so it's not
just about storing data. Previously I created log signatures for class2
and basically created the objects the "old fashioned" way.

Can I do this?
 
M

Martin Honnen

Is it possible to use JSON to "populate" objects that are already
defined? For instance, I have two "classes":

function class1() {
this.class2_array;
}

function class2() {
this.prop1;
this.prop2;
this.prop3;
this.prop4;
}

I want to create a bunch of class2 objects in the class1.class2_array
property.

With JSON I think all you can do is pass e.g.
var obj = { 'prop1': 1, 'prop2': 2, 'prop3': 3, 'prop4': 4 }
around, you could iterate over the property names then and initialize
your "class2 instance"
var c2 = new class2();
for (var propertyName in obj) {
c2[propertyName] = obj[propertyName];
}
And for..in might enumerate properties added to Object.prototype so
depending on libraries you might use you need to take care with that
construct not to add properties defined on the prototype.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top