简体   繁体   中英

Add an array to json object angularjs

I am trying to add a JSON array to a JSON object. My code is like this

$scope.packageElement = {
    "settings": [
        {
            "showNextPallet": true,
            "isParcelData": false,
            "isFreightData": true,
            "name": 0
        }
    ]
};

dataFromServer = {
    "pData": [
        {
            "PKUNIT": "LP",
            "PKDESC": "LARGE PKG",
            "PKDLEN": 30,
            "PKDWDT": 20,
            "PKDHTG": 20
        }
    ]
};

$scope.packageElement.concat(dataFromServer.pData);

But this throws an error

TypeError: undefined is not a function

at line

$scope.packageElement.concat(dataFromServer.pData);

My desired output is like this

var expectedOutPut = {
    "settings": [
        {
            "showNextPallet": true,
            "isParcelData": false,
            "isFreightData": true,
            "name": 0
        }
    ], "pData": [
        {
            "PKUNIT": "LP",
            "PKDESC": "LARGE PKG",
            "PKDLEN": 30,
            "PKDWDT": 20,
            "PKDHTG": 20
        }
    ]
};

Can any one point out what I am doing wrong here?

Simple:

$scope.packageElement.pData = dataFromServer.pData;

$scope.packageElement is an object, it doesn't have a concat function.

Or, a better option could be to use angular.extend() :

var expectedOutPut = angular.extend({}, $scope.packageElement, {'pData': dataFromServer.pData});

This way, you'll copy the objects, instead of modifying them.
Note: Keep in mind that angular.extend does not support recursive merge (deep copy).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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