How to make a recursive sum on a JSON object in Angular 6?

Asked

Viewed 129 times

3

Using Angular 6, how could fill the field total representing the total number of direct and indirect bosses of each employee?

I have the following data:

const employees = [
      {
        id: 1,
        firstName: 'a',
        lastName: 'A',
        position: 'PA',
        chefes: [2, 3],
        compensation: '123.00'
      },
      {
        id: 2,
        firstName: 'b',
        lastName: 'B',
        position: 'PB',
        chefes: [4],
        compensation: '456.00'
      },
      {
        id: 3,
        firstName: 'c',
        lastName: 'C',
        position: 'PC',
        compensation: '789.00'
      },
      {
        id: 4,
        firstName: 'd',
        lastName: 'D',
        position: 'PD',
        compensation: '1011.00'
      }
    ];
    return {employees};

In the above example, employee A has employee B and employee C as direct boss. But employee B has employee D as direct boss. That is, by adding direct + indirect bosses the employee a has 2+1=3 bosses the employee B = 1 and employees C and D have 0 bosses.

This would be the part of html that generates the new total of bosses (direct + indirect):

<dl>
  <dt>Título</dt>
  <dd>{{employee.position}}</dd>
  <dt>Compensation</dt>
  <dd>${{employee.compensation}}</dd>
  <dt>Total</dt>
  <dd>${{total????}}</dd>
</dl> 

1 answer

0


Oops... you can do it that way:

  employees = [
    {
      id: 1,
      firstName: 'a',
      lastName: 'A',
      position: 'PA',
      chefes: [2, 3],
      compensation: '123.00'
    },
    {
      id: 2,
      firstName: 'b',
      lastName: 'B',
      position: 'PB',
      chefes: [4],
      compensation: '456.00'
    },
    {
      id: 3,
      firstName: 'c',
      lastName: 'C',
      position: 'PC',
      compensation: '789.00',
      chefes: []
    },
    {
      id: 4,
      firstName: 'd',
      lastName: 'D',
      position: 'PD',
      compensation: '1011.00',
      chefes: []
    }
  ];

  contaChefes(idInformado) {
    let totalChefes = 0;

    this.employees.map(e => {

      if (e.chefes && e.id === idInformado){
        totalChefes += e.chefes.length;

        e.chefes.forEach(r => {
          totalChefes += this.contaChefes(r);
        })
      }
    })
    return totalChefes;
  }

<dl>
    <dt>Título</dt>
    <dd>{{employee.position}}</dd>
    <dt>Compensation</dt>
    <dd>${{employee.compensation}}</dd>
    <dt>Total</dt>
    <dd> {{ contaChefes(employee.id) }} </dd>
</dl>
  • In this case it is better to use reduce that map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.