我的状态如下:
{
id1: { houses: { name: 'x' }, cars: {} },
id2: { houses: { name: 'x' }, cars: {} },
...
}
我想返回一个如下所示的状态:
{
id1: { houses: {}, cars: {} },
id2: { houses: {}, cars: {} },
...
}
也就是说,我清空房屋入口。我不知道如何以不可变的reducer方式做到这一点,因为状态可以有很多条目(id1,id2,id3,..)
答案 0 :(得分:0)
棘手,但我尝试这样做的方式是使用Object.entries
和.reduce
const originalObj = {
id1: { houses: { name: 'x' }, cars: { dontTouch: 'me1'} },
id2: { houses: { name: 'x' }, cars: { dontTouch: 'me2'} },
id3: { houses: { name: 'x' }, cars: { dontTouch: 'me2'} }
};
const initalValue = {};
const objWithResetHouses =
Object.entries(originalObj)
.reduce((acc, [propName, value]) => {
// "copy" every property, then write over "houses" with an empty object
acc[propName] = {...value, houses: {}};
return acc;
}, initalValue);
console.log(objWithResetHouses);