0

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

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.