Search code examples
javascriptangularjsfor-loopnested-loops

how to map 2 arrays using 1 common json field (nested array)


I have 2 arrays that i am returning...in this case Employments and Users. They both have a common field 'id' and i want to use that field to map.

I can use a for loop to map it currently but since i am looping over a nested array...i only get to catch the mapping for the first part of the array.

my json objects:

     $scope.Users = [{
          id: 1,
          name: "Ryan"
      }, {
          id: 2,
          name: "Julie"
      }, {
          id: 3,
          name: "Stu"
      }, 
      {
          id: 4,
          name: "Holly"
      }];

      $scope.Employments = [{
          categoriesBag: [
            {
              category: [
                {
                  user_id: 1,
                  title: "manager"
                },
                {
                  user_id: 2,
                  title: "student"
                }
              ]
            },
            {
              category: [
                {
                  user_id: 3,
                  title: "worker"
                },
                {
                  user_id: 4,
                  title: "facilty"
                }
              ]
            }
          ]
      }];

the for loop that i am using to map the data:

$scope.getCategory = function(id) {
        var employmentCategories =  $scope.Employments.categoriesBag[0].category;
        for (var i = 0; i < employmentCategories[0].category.length; i++) {
          if (employmentCategories[0].category[i].user_id === id) {
            return employmentCategories[0].category[i].title;
          }
        }
      };    

since i am specifying that i only want the first array employmentCategories[0], the other two users are not included in the for loop. Is there a way for me to do a loop inside of a loop to loop over only the nested categories?


Solution

  • You can use a nested loop

    $scope.getCategory = function(id) {
        for (bag in $scope.Employments.categoriesBag) {
            for (category in bag.category) {
                if (category.user_id == id){
                   return category.title
                }
            }
        }
    }