简体   繁体   English

如何在angularjs中合并两个对象数组?

[英]How merge two objects array in angularjs?

I want to append following object array with existing one in angulajs for implementing load more feature. 我想在angulajs中追加跟随对象数组和现有的对象数组,以实现更多的加载功能。

ie,appending AJAX response with existing one each time. 即,每次附加现有的AJAX响应。

I have one variable, $scope.actions which contains following JSON data, 我有一个变量, $scope.actions包含以下JSON数据,

    {
    "total": 13,
    "per_page": 2,
    "current_page": 1,
    "last_page": 7,
    "next_page_url": "http://invoice.local/activities/?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 2,
    "data": [
        {
            "id": 2108,
            "action_type_id": 202,
            "user_id": 1
        },
        {
            "id": 2108,
            "action_type_id": 202,
            "user_id": 1
        }
    ]
}

I want to append following JSON response each time this variable. 我想在每次这个变量时追加JSON响应。

    {
    "data": [
        {
            "id": 2108,
            "action_type_id": 202,
            "user_id": 1
        },
        {
            "id": 2108,
            "action_type_id": 202,
            "user_id": 1
        }
    ]
}

I have tried with $scope.actions.data.concat(data.data); 我试过$scope.actions.data.concat(data.data);

but it is not working and getting following error message 但它无法正常工作并收到以下错误消息

$scope.actions.data.concat is not a function

You can use angular.extend(dest, src1, src2,...); 你可以使用angular.extend(dest, src1, src2,...);

In your case it would be : 在你的情况下,它将是:

angular.extend($scope.actions.data, data);

See documentation here : 请参阅此处的文档

https://docs.angularjs.org/api/ng/function/angular.extend https://docs.angularjs.org/api/ng/function/angular.extend

Otherwise, if you only get new values from the server, you can do the following 否则,如果只从服务器获取新值,则可以执行以下操作

for (var i=0; i<data.length; i++){
    $scope.actions.data.push(data[i]);
}

This works for me : 这对我有用:

$scope.array1 = $scope.array1.concat(array2)

In your case it would be : 在你的情况下,它将是:

$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function 

同样的问题,但我解决了这个问题

 $scope.actions.data = [].concat($scope.actions.data , data)

Simple 简单

var a=[{a:4}], b=[{b:5}]

angular.merge(a,b) // [{a:4, b:5}]

Tested on angular 1.4.1 测试角度为1.4.1

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

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