Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length detection in JSON (nested structure) - Angular View

Tags:

json

angularjs

Example JSON Structure

{
  "holding": [
    {
      "company": 1,
      "employee": [
        { "id": 1, "name": "John"},
        { "id": 2, "name": "Michael"},
        { "id": 3, "name": "George"}
      ]
    },
    {
      "company": 2,
      "employee": [
        { "id": 1, "name": "Madonna"},
        { "id": 2, "name": "Harry"}
      ]
    }
  ]
}

The structure above is available in the view as

{{ holding }}

Holding has 5 employees, how can I detect this in Angular? Is there a simple method? I need this possibility in the View, something like

{{ holding.length }}  // 2

What I need is (PSEUDO CODE):

{{ length of all employees in holding }} // 5

If possible: I need a view-only-solution, that doesn't modify the controller..

Controller-solutions below (answers) do work properly.


1 Answers

Use array's Reduce function. It takes a function that's called for each element of an array, taking the result of the last iteration (I called it count, but it doesn't have to be a numeric result) and the current element (company, since each element of holding represents a company). The parameter after the function is optional, and is used to specify an initial value for count, or whatever type of element you're working with.

var totalEmployees = parentObject.holding.reduce(function(count, company){
        return +count + +company.employee.length;
    }, 0);

You didn't provide a name to the object containing holding, so I just called it parentObject.

Another benefit is that this is vanilla JS, and so can be used even when Angular isn't available.

like image 115
Harris Avatar answered Sep 03 '26 19:09

Harris