json数组根据相同key值合并数组

我有一个这样的数组

[
    {
        "comments_id": 1,
        "comments_content":"xxxxx",
        "hasreply": 0,
        "reply_id": null,
        "reply_content": null,
    },
    {
        "comments_id": 2,
        "comments_content":"xxxxx",
        "hasreply": 1,
        "reply_id": 1,
        "reply_content": "xxxxxxx",
    },
    {
        "comments_id": 2,
        "comments_content":"xxxxx",
        "hasreply": 1,
        "reply_id": 2,
        "reply_content": "xxxxxxx",
    }
]

向根据相同comments_id,合并数组

[
    {
        "comments_id": 1,
        "comments_content":"xxxxx",
        "replys":[]
    },
    {
        "comments_id": 2,
        "comments_content":"xxxxx",
        "replys":[
            {
                "reply_id",1,
                "reply_content":"xxx"
            },
            {
                "reply_id",2,
                "reply_content":"xxx"
            },``
        ]
     }
]
阅读 3.4k
2 个回答

image.png

[].reduce(({m, replys}, { comments_id, comments_content, hasreply, reply_id, reply_content }) => {
    let comment = m[comments_id]
    if (!comment) {
      comment = m[comments_id] = { comments_id, comments_content, replys: [] };
      replys.push(comment)
    }
    if (hasreply) {
      comment.replys.push({reply_id, reply_content})
    }
    return {m, replys}
}, { m:{}, replys:[] }).replys
function format (arr) {
  let map = new Map();
  arr.forEach(o => {
    let {reply_id, reply_content, ...other} = o,
        id = o.comments_id,
        target;

    if (map.has(id)) {
      target = map.get(id).replys;
    } else {
      map.set(id, other);
      target = other.replys = [];
    }
    if (reply_id && reply_content) {
    target.push({
      reply_id,
      reply_content
    });      
    }
  });

  return [...map.values()];
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题