来自响应数据的javascript映射

问题描述 投票:0回答:1

我有一个laravel应用,在其中我要获取响应数据并将重复的内容复合到注释数组中,如下所示:

const dataMap = response.data.reduce((map, { taskt_id, comment_name, comment, ...extra }) => {
      let item = (map.has(taskt_id) ? map : map.set(taskt_id, { ...extra, comments: [] })).get(taskt_id)
      return item.comments.push({ comment_name, comment }), map

    }, new Map())

这一直运行得很好,但是现在我的响应数据中又返回了另一个数据集,该数据集也具有多个记录(一个类别,但是多个类别的详细信息),当我使用此方法时,它不再起作用并且我的新类别数组为空:

 const dataMap = response.data.reduce((map, { taskt_id, comment_name, comment, category, category_detail, ...extra }) => {
      let item = (map.has(taskt_id) ? map : map.set(taskt_id, { ...extra, comments: [], categories: [] })).get(taskt_id)
      return item.comments.push({ comment_name, comment }), map
      return item.categories.push({ category, category_detail }), map

    }, new Map())

所以也许我以错误的方式向此数组添加了另一个数组,但是如何以我的工作注释版本的表现方式向该映射添加更多的数组?

javascript
1个回答
0
投票

可能需要重构您的第二个更新的解决方案,以将双精度return删除,如下所示:

const dataMap = response.data.reduce((map, { taskt_id, comment_name, comment, category, category_detail, ...extra }) => {
  let item = (map.has(taskt_id) ? map : map.set(taskt_id, { ...extra, comments: [], categories: [] })).get(taskt_id)

  // push into comments
  item.comments.push({ comment_name, comment }), map

  // push into categories
  item.categories.push({ category, category_detail }), map

  // return item after comments and categories have been added
  return item;
}, new Map());

我还认为let item = ...应该是const item = ...,因为您在dataMap功能中没有在此之后重新分配项目。

© www.soinside.com 2019 - 2024. All rights reserved.