javascript - ReduxReducer - 根据 id 过滤数组,然后更改键/值对

标签 javascript ecmascript-6

我有一组评论,我想根据 ID 进行过滤并更改特定的键/值对。我的控制台日志函数返回数组中的正确项目,但我不确定获取 .filter 函数结果并将“liked”键从“false”更改为“true”的正确语法。如果扩展运算符适合这种情况,我可以使用它。

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function commentReducer(state = initialState.comments, action) {
  switch (action.type) {
    case types.ADD_COMMENT_LIKE_SUCCESS:
      const content = Object.assign({}, state);
      const likedComment = content.data.filter(comment => (
        comment.id === action.commentId
      ));
      console.log(likedComment[0]);
      break;

    default:
      return state;
  }
}

评论对象如下所示:

"data":{  
      "data":[  
         { id: '', comment: '', liked: false },
         { id: '', comment: '', liked: false },
         { id: '', comment: '', liked: false },
         { id: '', comment: '', liked: false }
      ],
      "cursor":"CkUKEQoEZGF0ZRIJCNrwhcWhvdUCEixqFGRldn5kZXZlbG9wbWVudC0xMzAwchQLEgdDb21tZW50GICAgLSe_-cKDBgAIAE=",
      "more":false,
      "count":4
   },

最佳答案

您正在使用具有正确语法的过滤器函数,尽管您的reducer应该返回具有该特定评论且喜欢的键值对为true的所有评论,这就是您可以继续使用 map 功能相同

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function commentReducer(state = initialState.comments, action) {
  switch (action.type) {
    case types.ADD_COMMENT_LIKE_SUCCESS:
      const content = Object.assign({}, state);
      content.data =  content.data.map(comment => {
                      const newObj = {...comment};
                      if(newObj.id === action.commentId)
                      { 
                            newObj.likeKey = true;
                      }
                      return newObj;
      }); 
     console.log(content);
     return content;   
    default:
      return state;
  }
}

Map 函数将返回您到目前为止拥有的所有评论,并更改特定的评论对象。希望这会有所帮助。

关于javascript - ReduxReducer - 根据 id 过滤数组,然后更改键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878654/

相关文章:

javascript - 为什么这个 javascript 片段不起作用?

javascript - 从动态创建的控件中进行 ajax 调用

javascript - 名称 id 或类中的正则表达式?

javascript - Parse.com CloudCode 中的解构赋值

javascript - Javascript 中优雅的数组转换

ecmascript-6 - 在服务 worker 中使用 browser.js

javascript - 如何在reactjs和meteor中显示加载器?

javascript - 使用 jquery 从 html 表中删除动态添加的行时出现问题

Javascript 清除 DOM

javascript - 如何确定 Observable.merge 中哪些 observable 发生了更改?