[英]How do I add a property on a property of an object?
I am using normalizer on a redux state, and I have to add a loading object for the UI indicator,我在 redux 状态下使用 normalizer,我必须为 UI 指示器添加一个加载对象,
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:这就是我想要做的,在 obj1 和 obj2 属性上:我想动态添加这个对象:
loading:{ update_a: false }
How do I do it?我该怎么做? I don't what to manipulate the array on the Axios response;
我不知道如何操作Axios响应上的数组; 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
你可以使用
Object.entries
做类似的事情并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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.