Answer the question
In order to leave comments, you need to log in
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,
}
]
Store = {
Type0: [ { name: Карандаш, type: 0 }, { name: Ручка, type: 0 } ],
Type1: [ { name: Бумага, type: 1 } ],
Type2: [ { name: Кресло, type: 2 } ],
Type6: [ { name: Стол, type: 6 } ],
Type10: [ {name: Стул, type: 10 } ]
}
Answer the question
In order to leave comments, you need to log in
const result = array.reduce((acc, el) => {
const key = 'Type' + el.type;
acc[key] = acc[key] ? [...acc[key], el] : [el];
return acc;
}, {});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question