Reputation: 3705
I have this code that i use in a redux reducer:
case 'REMOVE_FL_EVENT' :
return{
...state,
events: Object.keys(state.events).map(group => {
return state.events[group].filter(item => item.id !== action.id)
})
}
What happens here is that the state.events is an object, where every key is the name of the group of it's events, the value is an array with the events. What i want to do is when i convert the object into an array with map, if the filter happened convert back to it's original state, where state.events is not an array, but an object, with the original names of the keys.
Upvotes: 1
Views: 57
Reputation: 3115
There is no need to use map
, you could use reduce
only, something like:
{
...state,
events: Object.keys(state.events).reduce(
(obj, event) => ({
...obj,
[group]: state.events[group].filter(item => item.id !== action.id)
}),
{}
)
};
The reduce
has the following signature:
arr.reduce(callback[, initialValue])
So in our script, we are giving an empty object as the initial value for the accumulation.
Upvotes: 1
Reputation: 858
With standard JS, you can use reduce
to convert the array back to an obj:
arr.reduce((acc, o) => Object.assign(acc, o), {})
Using ramda.js
you can filter Objects and their nested properties. https://ramdajs.com/docs/#filter
Upvotes: 1
Reputation: 676
You can use map/reduce for this purpose. First map it and then reduce it into an object.
case 'REMOVE_FL_EVENT' :
return{
...state,
events: Object.keys(state.events).map(group => {
return { [group]: state.events[group].filter(item => item.id !== action.id) }
}).reduce((obj, event) => Object.assign(obj, event), {})
}
The output will be an object with keys as groups. Let me know if it works.
Upvotes: 1