I am using normalizer on a redux state, and I have to add a loading object for the UI indicator,
So if we assume this is my normalized object:
const myState = {
obj1: {
a:1,
b:2
},
obj2: {
a:2,
b:3
}
}
This is what I want to do, on properties obj1, and obj2: I want to dynamically add this object:
loading:{ update_a: false }
How do I do it? I don't what to manipulate the array on the Axios response; I'm doing it on the reducers.
我们可以这样做:
Object.keys(myState).reduce((acc, key) => {acc[key] = {...myState[key],loading:{ update_a: false } }; return acc;},{})
We'll pull the existing state apart and build a new version with the added property we want:
Object.fromEntries(
Object.entries(myState)
.map(([key, obj]) => [
key,
{
...obj, // copy properties from the existing obj
loading: { // and add the loading property
update_a: false
}
}
])
);
Hopefully a little easier to read than my one-line version in the comments.
You can do something like that using Object.entries
and reduce
const myState = { obj1: { a: 1, b: 2 }, obj2: { a: 2, b: 3 } } const res = Object.entries(myState).reduce((all, [key, value]) => { all[key] = { ...value, loading: { updated_a: false } } return all; }, {}) console.log(res)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.