[Vuejs]-Array not being pushed as a new index, but as a new array

1👍

Let’s see if I can make it clear to you:

var commentArray = []; 
// here you are creating an empty array called commentArray 

commentArray.push({
    'text': comment,
    'user': vm.user
}); 
// Here you define an object, with 2 properties (text and user) 
// and push it to commentArray you created so 
// commentArray = [{'text': comment, 'user': vm.user}];

reference.reference.comments.push(commentArray);
/// here you push an array (commentArray) into another array (comments)
// so reference.reference.comments will be [[{'text': comment, 'user': vm.user}]];

I’ll do a working example in a moment.

var comments = [];
var commentArray = [];

commentArray.push({
    'text': 'comment',
    'user': 'someuser'
});
console.log('comments:', comments);
console.log('commentArray:', commentArray);

comments.push(commentArray);
console.log('comments:', comments);
console.log('commentArray:', commentArray);

So you shouldn’t create an intermediary array. You should create only the object. Like this:

var comment = {
    'text': comment,
    'user': vm.user
};

reference.reference.comments.push(comment);

or more directly like this:

reference.reference.comments.push({
    'text': comment,
    'user': vm.user
});

0👍

Try this, you want to push a single comment into your comments array, not an array into an array.

var comment = {
    'text': comment,
    'user': vm.user
};

reference.reference.comments.push(comment);

Leave a comment