如何合并属于 Reducer 的对象内的对象属性

How to merge object properties inside an object belonging to a Reducer

我正在尝试使用 'comments' 对象实现一个 reducer,该对象包含由某个 ID 索引的评论数组。我想合并而不是替换 'comments' 对象中的属性。

现在我有这个:

commentsReducer {
   comments: {}
   1: Array[9]
   2: Array[5]
   isFetchingComments: true
   lastUpdated: null
}

我的 Reducer 函数:

function commentsReducer(state = {
   isFetchingComments: false,
   lastUpdated: null,
   comments : {}
   },action){

  switch(action.type){      
    case RECEIVE_COMMENTS:
      var new_cm = {[action.pid]: action.comments};
      return Object.assign({}, state, new_cm); 

  }
}

我想做什么:

commentsReducer {
   comments { 
      1: Array[9],
      2: Array[5]
   }
   isFetchingComments: true
   lastUpdated: null
}

改变

var new_cm = {comments:{[action.pid]: action.comments}};

它应该可以解决问题

编辑

如果您想添加更多评论,那么

var new_cm = {comments: Object.assign({}, state.comments, {[action.pid]: action.comments})};

试试jQuery的功能: $.extend();


示例:

var obj1 = {
  a: 1,
  b: 2
};
var obj2 = {
   b:3,
   c:4
};
var obj3 = $.extend({},obj1,obj2);
console.info(obj3);

结果是: { a:1, b:3, c:4 }


希望这对你有用...

你可以试试这个。

switch(action.type){      
  case RECEIVE_COMMENTS:
    var new_cm = Object.assign({}, state.comments, {[action.pid]: action.comments});
    return Object.assign({}, state, new_cm); 

}