-2

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?

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • 3
    Well `commentArray` is indeed an *array*. It's not clear what's surprising about the result of pushing an array into another array; the whole array is added. – Pointy Mar 21 '19 at 21:06
  • commentArray = {text, user} – u_mulder Mar 21 '19 at 21:06
  • 1
    Change it to: `reference.reference.comments.push(...commentArray)` – adiga Mar 21 '19 at 21:24
  • Possible duplicate of [Push array items into another array](https://stackoverflow.com/questions/4156101/push-array-items-into-another-array) – adiga Mar 21 '19 at 21:25

2 Answers2

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
});
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
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);
NickAndrews
  • 496
  • 2
  • 9