Javascript push not working in array inside object

Javascript push not working in array inside object
0

#1

As you can see in the code, i tried to dynamically create array values inside an object, it doesn’t have a problem when debugging, but when i tried to use push method in the array it throws an error.I am working on Angular 4 with Typescript.

 private newsFeeds=[
    {
      avatarUrl:'../assets/fb/avatar.png',
      userName:'Karim Benzema',
      time:'16 minutes ago',
      caption:'Wow!!!',
      imageUrl:'https://upload.wikimedia.org/wikipedia/commons/e/ec/Ara_ararauna_Luc_Viatour.jpg',
      like:'Like',
      numberOfLikes:2,
      comments:["hello"],
      isCommentEnable:false
    },
   {
      avatarUrl:'../assets/fb/avatar2.png',
      userName:'Unknown Singh',
      time:'2 hrs ago',
      caption:'Pc:Unknown',
      imageUrl:'https://i.pinimg.com/736x/50/e0/b6/50e0b65efd2d634053d7a8d1cd9d94fc--so-funny-funny-
      stuff.jpg',
      like:'Like',
      numberOfLikes:3,
      comments:[],
      isCommentEnable:false
    }
];

postComment(index,value){
       console.log(index);
       console.log(this.newsFeeds[index]); 
       this.newsFeeds[index].comments.push(value.toString()); //Throws runtime error 'comments.push is 
                                                                                                  //not a function'
   
  }

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

If you put:

console.log(typeof this.newsFeeds[index].comments)); 

then what do you see displayed in the console? I assume it is not “object”.


#4

when I typed that in console it gives me the type object and indeed it’s an object…I still don’t get why the push is not working,I am working on Ionic 3 with angular 5/TypeScript and I am calling the postComment method on input box’s keyup.enter event…my console logs inside the postComment method gives me the correct values of index and value but when it comes to the push part then it throws a runtime error saying ‘Push is not a function’…BTW when I replaced push with concat then it works fine…