更新具有多个键的对象的状态

时间:2017-08-23 21:07:27

标签: redux

我的状态如下:

{ id1: { houses: { name: 'x' }, cars: {} }, id2: { houses: { name: 'x' }, cars: {} }, ... }

我想返回一个如下所示的状态: { id1: { houses: {}, cars: {} }, id2: { houses: {}, cars: {} }, ... }

也就是说,我清空房屋入口。我不知道如何以不可变的reducer方式做到这一点,因为状态可以有很多条目(id1,id2,id3,..)

1 个答案:

答案 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);