简体   繁体   English

将一个数组复制到另一个数组时出现问题

[英]Issue when copying one array into another

I am trying to put the contents of an array into another. 我试图将一个数组的内容放入另一个。 I have this json ($scopeProducts)... 我有这个json($ scopeProducts)...

{
"ID": "...",
"Groups": [
    {
        "Products": []
    }
{
        "Other": []
    }
]
}

And I am trying to add the following json into the 'Products' array ($scope.selectedProducts)... 我正在尝试将以下json添加到'Products'数组($ 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... 我正在使用JavaScript推送功能...

$scopeProducts.Groups[0].Products.push($scope.selectedProducts); 

Could anyone tell me how to do this correctly without creating the double array [[]] ? 谁能告诉我如何正确执行此操作而不创建double数组[[]]? Many thanks 非常感谢

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): 如果要附加它(除非Angular具有某些实用程序功能):

$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 . 这有点棘手:它使用Function#apply调用带有多个参数的push ,每个参数用于$scope.selectedProducts每个条目。 This is because JavaScript arrays don't have a native append method; 这是因为JavaScript数组没有本机的append方法。 the closest they come is concat , which creates a new array. 它们最接近的是concat ,它将创建一个数组。 But the above works for append functionality. 但以上内容适用于附加功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM