BSmall
BSmall

Reputation: 28

Add array as element of another Array

I have an array like this

$scope.dogs = [
  { id: 1, breed: 'German Shepherd' }, 
  { id: 2, breed: 'Collie' }
]

And a second array like this:

$scope.owners = [
  { name: 'Mary', breedowned: 'German Shepherd' }, 
  { name: 'Bill', breedowned: 'German Shepherd' }, 
  { name: 'Bob',  breedowned: 'Collie' }
]

I want to push the list of owners into the list of dogs like so basically creating:

$scope.dogs = [
  { id: 1, breed: 'German Shepherd', owners: [...] }
]

I tried to use forEach and push the owners into the dogs array, but it does not work.

       angular.forEach($scope.dogs, function (value, key) {

            for (x = 0; x < $scope.owners.length; x++) {
                if ($scope.owners[i].breedowned == value.breed) {
                    $scope.dogs[key].owners.push($scope.owners[i])
                }
            }
    });

Thanks for any help!

Upvotes: 0

Views: 40

Answers (3)

Michele Ricciardi
Michele Ricciardi

Reputation: 2117

Here a better solution that only goes through the owners array once and only through the dogs array once.

var tracker = $scope.owners.reduce(function(trackerObj, owner){
   var breedowned = owner.breedowned;
   trackerObj[breedowned] = trackerObj[breedowned] || [];
   trackerObj[breedowned].push(owner);
   return trackerObj;
}, {});
$scope.dogs.forEach(function(dog){
   dog.owners = tracker[dog.breed];
});

Upvotes: 0

agmcleod
agmcleod

Reputation: 13621

You didnt mention any errors, but I see an issue with you missing var in front of the x in the for loop, and also owners is not initialized in the dog object. Here's a consistent nested loop solution:

angular.forEach($scope.dogs, function (dog) {
    angular.forEach($scope.owners, function (owner) {
        if (owner.breedowned == dog.breed) {
            dog.owners = dog.owners || []
            dog.owners.push(owner)
        }
    })
})

Upvotes: 0

illeb
illeb

Reputation: 2947

If you don't want any form of dependency, just use Array.prototype.push.apply, this way:

Array.prototype.push.apply($scope.owners, $scope.dogs);

Upvotes: 1

Related Questions