ImmutableJS how to simplify a filter and update logic

こ雲淡風輕ζ 提交于 2019-12-25 03:14:27

问题


The following is my structure of data

[
  {
    "id": 1,
    "title": "Welcome to my playground",
    "description": "This is so fun to play with, you will like it <3",
    "comments": [
      {
        "id": 1140406,
        "comment": "this is an example comment",
        "postId": 1
      }
    ]
  },
  ...
]

And I'm trying to use immutable js to do this operation

  1. Get all the posts
  2. Search for a post I want to add comment to
  3. Adding the comments when the post is found

The following is my code

posts = posts.map((post) => {

            if(post.get('id') == payload.post_id) {

                return post.update('comments', (comments) => {    
                    return comments.push(Map({
                        id: payload.id,
                        comment: payload.comment
                    }));
                });
            }

            return post;
        });

But I assume this pattern is very common and there should be a simpler way to do this in immutableJS. Any advice will be helpful, thanks.


回答1:


First off, it's worth mentioning that your Data structure is Immutable Lists and Maps.. not JS Arrays and Objects.

OK, without changing your data structure you could do:

posts.map(post => post.get('id') === payload.post_id ?
  post.update('comments', comments.push(payload) :
  post)

If you were to change your data structure, and instead of having a List of posts, had a Map of post's with their ID as the key you could just do:

post.updateIn([payload.post_id, 'comments'], comments => comments.push(payload))

BTW you can use push or concat here, both will function the same.

Also, if comments may be undefined, you can provide a "noSetValue" as a List (https://facebook.github.io/immutable-js/docs/#/List/updateIn):

posts.map(post => post.get('id') === payload.post_id ?
  post.update('comments', Immutable.List([]), comments.push(payload) :
  post)

post.updateIn([payload.post_id, 'comments'], Immutable.List([]), comments => comments.push(payload))


来源:https://stackoverflow.com/questions/34890025/immutablejs-how-to-simplify-a-filter-and-update-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!