M
M
mr jeery2018-08-10 14:20:32
API
mr jeery, 2018-08-10 14:20:32

How to split a JSON array of elements into an indefinite number of arrays?

Good afternoon.
I get an array of objects from the API, where the type property determines the category of the product, I need this array to be transformed into several depending on the category in reduxStore.
For example action.data looks like this.

[
{
name: Карандаш,
type: 0
},
{
name: Ручка,
type: 0
},
{
name: Бумага,
type: 1
},
{
name: Кресло,
type: 2,
},
{
name: Стол,
type: 6,
},
{
name: Стул,
type: 10,
}
]

And in the end ReduxStore should look like this
Store = {
Type0: [ { name: Карандаш, type: 0 }, { name: Ручка, type: 0 } ],
Type1: [ { name: Бумага, type: 1 } ],
Type2: [ { name: Кресло, type: 2 } ],
Type6: [ { name: Стол, type: 6 } ],
Type10: [ {name: Стул, type: 10 } ]
}

Help with the implementation, please.
And is it legal to do this in a reducer? Maybe a middleware would be a better fit for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-10
@jeerjmin

const result = array.reduce((acc, el) => {
  const key = 'Type' + el.type;
  acc[key] = acc[key] ? [...acc[key], el] : [el];

  return acc;
}, {});

Legally. The main thing is to stick to one style in organizing the code so that it doesn’t happen that in one place the data is converted in the reducer, in another in the middleware.
In addition, for the particular needs of the component, the data can be converted in the selectors passed to mapStateToProps.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question