简体   繁体   中英

How to concatenate or merge two arrays

I have two array variables: var1 and var2 .

$scope.var1 = {
"0":{"subjectId":"1","subjectShortName":"English","subjectCode":null,"IsSelected":true},
"1":{"subjectId":"2","subjectShortName":"Hindi","subjectCode":null,"IsSelected":true}
};

$scope.var2 = {"classId":"3","typeOfSubject":"main"}

How I can merge or concatenate these two arrays to get the kind of array below? Basically I want to add all subjectId as Key to second array.

$scope.var2 = {"classId":"3","typeOfSubject":"main", "subjectId":"{1,2}"}

In your exemple you are using objects not arrays. But I leave here how to join two objects. https://docs.angularjs.org/api/ng/function/angular.extend

In your case:

$scope.new_var = angular.extend({}, $scope.var1, $scope.var2)

.

If you intend to use array I do not know a native function in angularjs.

You can use jquery > http://api.jquery.com/jquery.merge/

Or javascript

var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);

Your expectation is not clear. Anyway following your request here it is. It will add the subjectIds of var1 into var2 as a list of integers.

var subjectIds = [];
for(var k in $scope.var1) {
   subjectIds.push(parseInt($scope.var1[k].subjectId));
}
$scope.var2.subjectId = subjectIds.join(', ');

Results into

{ classId: '3', typeOfSubject: 'main', subjectId: "1, 2" }

It looks like you want to merge these objects so the result looks like:

{
    "classId": "3", 
    "typeOfSubject": "main", 
    "subjectId": {
        "1": {"subjectId": "1", "subjectShortName": "English", ...}
        "2": {"subjectId": "2", "subjectShortName": "Hindi", ...}
    }
}

This doesn't require any angular support to accomplish, but you can use angular.forEach to iterate your var1 object easily:

$scope.var2.subjectId = {};

angular.forEach($scope.var1, function(subject){
    this[subject.subjectId] = subject;
}, $scope.var2.subjectId); //set "this" to the member of var2 we're populating

These are objects, not array.. note that array have this [] brackets, while objects are {} just like your code.. in this case you want to join a new object into your constructed object..

Your problem has already been solved in this post here

But if you wish to see a smaller code.. would be using extends function in AngularJS according to the docs here

angular.extends(yourObject, objectToJoin, ...);

note that this function is inherited from jQuery and you can check the jQuery docs version in here

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