My object contains the following format:
[
{ },
{ }
]
But the way my code is written, it adds it in as,
[
[
{ }
],
[
{ }
]
]
Not sure what's going on, here is my code:
var commentArray = [];
commentArray.push({
'text': comment,
'user': vm.user
});
reference.reference.comments.push(commentArray);
Something like this works:
reference.reference.comments.push({
'text': comment,
'user': vm.user
});
But I want to push commentArray
?
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
});
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.