0

I have a an object PARENT defined like the following

function PARENT(name, childs){
   this.name=name;
   var childsArray=New Array();

   childs.forEach(function(child_info) {
          childsArray.push(new CHILD(child_info));
      })
      this.childsArray=childsArray;
}

Then there is another object CHILD defined as

function CHILD(_child_info) {
  this.name = child_info.name;
  this.age  = child_info.age;

 }

Given an array of PARENT objects I would like to get the following json object

[
{name:"parent 1 name",
childs : [
           {
             name:"child 1 name",
             age:"child 1 age"  
           },
           {
             name:"child 2 name",
             age:"child 2 age"  
           },
           {
             name:"child 3 name",
             age:"child 3 age"  
           }
         ]
}, ...
{name:"parent n name",
childs : [
           {
             name:"child 1 name",
             age:"child 1 age"  
           },
           {
             name:"child 2 name",
             age:"child 2 age"  
           }
         ]
}
]

but when I try to stringify the array of PARENT I get an empty JSON object {}

How can I achieve this?

Bruno C
  • 199
  • 13
  • JSON doesn't have any way to represent user-defined objects. It's a language-agnostic serialization format. – Barmar Mar 19 '20 at 19:48
  • But you should still get the objects, you just won't get the prototypes and methods. – Barmar Mar 19 '20 at 19:50
  • Please create a [mcve] demonstrating the problem. – Barmar Mar 19 '20 at 19:50
  • Thanks Barmar. I ended up writing a function for the user defined object that build the string and then I parse it ... right now I face another issue as the returned JSON is inside a Promise value object – Bruno C Mar 19 '20 at 20:23
  • 1
    See https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Barmar Mar 19 '20 at 20:27

0 Answers0