2

In a NgRx Angular 5 project, there is a use of the reduce function i don't really understand. I would appreciate some help

Basically the code iterates an array of object and the array looks like this:

[{
   id: '0',
   message: 'work',
   done: false
 },
 {
   id: '1',
   message: 'movie',
   done: false
 },
 {
   id: '2',
   message: 'Play',
   done: false
 }]

In my NgRx reducer, there is the following block of code :

case todosAction.FETCH_TODO_SUCCESS: {
  return {
    ...state,
    //action.payload contains above array of objects
    datas: action.payload.reduce((accumulateur, iteration) => {
      accumulateur[iteration.id] = iteration;
      return accumulateur;
    }, { ...state.datas }),
    loading: false,
    loaded: true,
    error: null 
  };
}

The state i'm using looks like this:

export interface TodoState {
  datas: {
    [todoId: string]: Todo
  }
  loading: boolean;
  loaded: boolean;
  error: any;
}

We use the reduce function here to transform the original source which is an array of object to entities ( a key which is an id associated to a todo object). I understand the reason why we use this function but i don't understand its inner code:

action.payload.reduce((accumulateur, iteration) => {
          accumulateur[iteration.id] = iteration; // <-- AS FAR AS I UNDERSTAND, ACCUMULATOR IS NOT AN ARRAY, HOW CAN WE ACHIEVE SUCH A THING
          return accumulateur;
        }, { ...state.datas })

Thank you in advance for helping me to put some light on this.

Slrg
  • 129
  • 6

1 Answers1

1

Imagine that

state.datas equals to:

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  }
}

action.payload equals

[{
  id: '1',
  message: 'World',
  done: false
}]

After the reducer returns you will end up with

{
  '0': {
    id: '0',
    message: 'Hello',
    done: false
  },
  '1': {
    id: '1',
    message: 'World',
    done: false
  }
}

The important thing to note is that the id is a string. You can have an object with a key of '0'. It's no different than using any other string.

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • Thank you for helping, In the reducer, do we agree that the initial accumulateur value is { id: '0', message: 'work', done: false } ? This is not an array, why can we use this : accumulateur[iteration.id] = iteration; – Slrg Apr 19 '18 at 09:53
  • The initial value is `{ '0': { id: '0', message: 'Hello', done: false } }` . You can set properties values on objects like this: `const x = {}` `x['0'] = 'hello`'. – Tomasz Kula Apr 19 '18 at 09:55
  • It helped me. Thank you ! – Slrg Apr 19 '18 at 12:42