Reputation: 1895
I am trying to put the contents of an array into another. I have this json ($scopeProducts)...
{
"ID": "...",
"Groups": [
{
"Products": []
}
{
"Other": []
}
]
}
And I am trying to add the following json into the 'Products' array ($scope.selectedProducts)...
[
{
"ProductCode": "Code1",
},
{
"ProductCode": "Code1",
},
]
and I end up getting this...
{
"ID": "...",
"Groups": [
{
"Products":
[
[
{
"ProductCode": "Code1",
},
{
"ProductCode": "Code1",
},
]
]
}
{
"Other": []
}
]
}
... which is wrong (check the double [[ in the products array). I am using the javascript push function...
$scopeProducts.Groups[0].Products.push($scope.selectedProducts);
Could anyone tell me how to do this correctly without creating the double array [[]] ? Many thanks
Upvotes: 0
Views: 44
Reputation: 1074495
Your code is pushing an array into another array as an entry, not appending the entries to it.
If you want to append it (barring Angular having some utility function):
$scopeProducts.Groups[0].Products.push.apply($scopeProducts.Groups[0].Products, $scope.selectedProducts);
That's a bit tricky: It uses Function#apply
to call push
with multiple arguments, one for each entry in $scope.selectedProducts
. This is because JavaScript arrays don't have a native append
method; the closest they come is concat
, which creates a new array. But the above works for append functionality.
Upvotes: 2