Is there a way to get just a shallow copy of the below to only get one layer deep? I have a means to fix this using a completely different design but I was wondering if anyone else had ran into what I am trying to convert to a string before.
var SomeObjClass = function() {
var self = this;
this.group = {
members: [self]
};
};
var p = new SomeObjClass();
var str = JSON.stringify(p);
It's a little unclear what you're asking, but if your goal is to simply stringify a circular object, you'll have to override toJSON
to specify how you'd like your object to be represented
function SomeObjClass () {
var self = this;
this.group = {
members: [self]
};
}
SomeObjClass.prototype.addMember = function(m) {
this.group.members.push(m);
};
// when stringifying this object, don't include `self` in group.members
SomeObjClass.prototype.toJSON = function() {
var self = this;
return {
group: {
members: self.group.members.filter(function (x) {
return x !== self
})
}
};
}
var a = new SomeObjClass();
var b = new SomeObjClass();
a.addMember(b);
console.log(JSON.stringify(a))
This is probably the best I can help you without seeing more of your code. I don't know how you're using this code, but whatever the case, this is probably not the best design for your class. If you share the rest of the class and the code that uses it, we can probably help you more effectively.