J.DD J.DD - 4 months ago 13
Javascript Question

How to put object into another object Angular / Javascript

I'm making an app and I'm stuck when trying to push an array into another array.
I get an error "Cannot read property 'push' of undefined."

This is the object :

CARDS: any [] {
channel: "facebook"
date: "2016-01-07"
comments: [
{
content: "Hey would you look at this card?",
user: "John Appleseed",
avatar: "url"
},
{
content: "I like this card!",
user: "John Doe",
avatar: "url"
}
]
},
{
channel: "facebook"
date: "2016-01-07"
comments: [
{
content: "Hey would you look at this card?",
user: "Jane Doe",
avatar: "url"
}
]
};


I have an option in my app to add a comment to a card. Therefore I created:

newComment = {
content: "",
user: "",
avatar: ""
};


And with a button I call the submitComment function:

submitComment(comment) {
console.log(this.newComment);
this.comment.push(newComment);
}


My HTML looks like this (fyi: I'm working with ionic, that explains the ion-input)

<ion-input type="text" placeholder="Type a comment..." [(ngModel)]="newComment.content"></ion-input>
<button (click)="submitComment(comment)">Send comment</button>


I did a console.log in my submitComment function and it displays the right information. But the push doesn't work. I get an error 'Cannot read property 'push' of undefined. I tried "this.newComment" between the brackets, but it's not working either.

I'm just starting to know Angular/JS, so it's probably something simple I just cannot figure out. Thanks in advance for your help :-)

EDIT: I forgot to add. I do an *ngFor="let comment of card.comments" to display al the comments. Therefore I just use the "comment" in further HTML.

Answer

Your problem is because the comment variable you provide to the submitComment method is null. So you can't call any method (specially push) on it...

Otherwise your CARDS property doesn't seem to be correctly defined. You would define it this way rather:

CARDS: any [] = [
  {
    channel: "facebook"
    date: "2016-01-07"
    comments: [
      { 
        content: "Hey would you look at this card?",
        user: "John Appleseed",
        avatar: "url"
      },
      { 
        content: "I like this card!",
        user: "John Doe",
        avatar: "url"
      }
    ]
  },
  {
    channel: "facebook"
    date: "2016-01-07"
    comments: [
      { 
        content: "Hey would you look at this card?",
        user: "Jane Doe",
        avatar: "url"
      }
    ]
  }
];
Comments