#JSON.stringify on nested class instance

12 messages · Page 1 of 1 (latest)

deep python
#

Why does this example show only parent parent properties when using JSON.stringify ?
how can I get around it ?

class Parent {
    id: string;
    name: string;
    children?: Child[]

    constructor(id:string ,name: string){
        this.id = id
        this.name = name
    }
}
class Child {
    child_id: string;
    child_name: string;

    constructor(id: string,name: string){
        this.child_id = id
        this.child_name = name;
    }
}

const p = new Parent("p1","Parent 1")
const c1 = new Child("c1","Child 1")
p.children?.push(c1);
console.log(JSON.stringify(p))
snow gateBOT
#
sachn#0

Preview:```ts
class Parent {
id: string
name: string
children?: Child[]

constructor(id: string, name: string) {
this.id = id
this.name = name
}
}
class Child {
child_id: string
child_name: string

constructor(id: string, name
...```

deep python
#

thanks removed the longer link

somber junco
#

@deep python Your issue is:

#
p.children?.push(c1);
#

That pushes c1 if p.children is defined and otherwise does nothing.

deep python
#

humh, but if I try to remove ? ts shouts at me as children could be undefined - I should initialize a blank array in the constructor ? or something else ?

somber junco
#

Yeah, I would probably have the children array always be there but sometimes be empty.

#

Or you can do something like:

#
(p.children ??= []).push(c1);
deep python
#

thanks, using a blank array worked 🙂

somber junco
#

Though, uhh, you might want to use semi-colons:

const c1 = new Child("c1","Child 1")
(p.children ??= []).push(c1);

This is interpreted as: