Michael Wilson
Michael Wilson

Reputation: 1579

What is the correct way to add a property of specific items from a different array to an object

I have two different arrays, one holds categories whilst the other holds pages.

Categories array:

$scope.categories = [{
  id: 1,
  name: "Test category"
}];

Pages array:

$scope.pages = [{
  id: 1,
  name: "Test page",
  category: 1
}];

I would like to add all associated pages to its category. This can be achieved by knowing if the category property for a page is equal to a category's id.

At the moment, I wrote a function which loops through

function getPagesById(categoryId) {

  var tmp = [];

  for (var i = $scope.pages.length - 1; i >= 0; i--) {
    if($scope.pages[i].category == categoryId) {
      tmp.push($scope.pages[i]);
    }
  };

 return tmp;

}

function mergePages() {

  var tmp = $scope.categories;

  for (var i = tmp.length - 1; i >= 0; i--) {

    tmp[i].pages = getPagesById(tmp[i].id);

  };

  return tmp;

}

$scope.categories = mergePages();

Is this the correct Angular way to achieve this?

Upvotes: 2

Views: 58

Answers (1)

Ankh
Ankh

Reputation: 5718

There is no right or wrong answer to this. If I interpret your question as 'Can Angular simplify this?' then yes, it can.

You can use Angular filters to condense your mergePages function into something like this:

function mergePages()
{
    angular.forEach($scope.categories, function (category)
    {
        category['pages'] = $filter('filter')($scope.pages, {category: category.id});
    });
}

This will populate $scope.categories with the appropriate pages by comparing the category ids in the filter.

Here's a fiddle that demonstrates it working.

Upvotes: 3

Related Questions