Search code examples
javascriptangularngrxreducersngrx-entity

Using Array.reduce function with objects in a NgRx application


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.


Solution

  • 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.