javascript - Create just one object from an array of objects, to be used in a redux reducer -


i have array of objects like

[   {id: example1, count: 2}, {id: example2, count:2} ] 

which turn object like

{   example1: { id: example1, count: 2},   example2: { id: example2, count: 2}, } 

...and on.

this supposed used in redux reducer uses es6 if in there available or in lodash.

answer:

for clarity, ended doing @james-emanon suggested in answer. of course matter of using reduce.

        case actiontypes.fetch_snapshots_success:           let snapshots = action.payload.reduce((p, c) =>             object.assign({},               p, {                 [c.id]: c               }             ), {}           )            return object.assign({},             state, {               isfetching: false,               lastupdated: action.meta.receivedat             },             snapshots           ) 

how this? (using es6 conventions)

// assuming action pass object var = [   {id: 'example1', count: 2}, {id: 'example2', count:2} ]      // snippet reducer    case type.some_case_constant:     let newobj = action.yourarrayofobj                  .reduce((p,c) => {                      return {...p, [c.id]: c}                  }, {})    return {      ...state,      newobj    } 

or

action.yourarrayofobj                      .reduce((p,c) => {                              p[c.id] = c                              return p                      }, {}) 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -