我在Stack Overflow上看到了许多关于这个主题的问题,然而,它们似乎都返回了单个对象.(不是我想要的)

我下面有一个数组;

const locations = [
    {"city": "London", "district": "Brixton", "id": "Eue3uFjUHKi6wh73QZLX"},
    {"city": "Manchester", "district": "Bury", "id": "QZiiUBgzZaJt2HcahELT"},
    {"city": "London", "district": "Hackney", "id": "v2itdyO4IPXAMhIU8wce"}
]

我想将此数组映射为基于"city"键的部分.

我的预期yields 是;

 [
    {
       city: "London",
       data: [
          {
             city: "London",
             district: "Brixton",
             id: "Eue3uFjUHKi6wh73QZLX"
          },
          {
             city: "London",
             district: "Hackney",
             id: "v2itdyO4IPXAMhIU8wce"
          }
       ]
    },
    {
       city: "Manchester",
       data: [
          {
             city: "Manchester",
             district: "Bury",
             id: "QZiiUBgzZaJt2HcahELT"
          }
       ]
    }
 ]

我已经try 了下面的方法;

const groupedLocations = locations.reduce((groups, item) => {
  const { city } = item;
  if (!groups[city]) {
    groups[city] = [];
  }
  groups[city].push(item);
  return groups;
}, {});

但是,这返回的是对象而不是array.

推荐答案

以下是一个有效的代码:

const groupedLocations = locations.reduce((groups, item) => {
  const { city } = item;
  
  let relatedGroup = groups.find((group) => group.city === city);
  if (!relatedGroup) {
    relatedGroup = { city, data: [] };
    groups.push(relatedGroup);
  }

  relatedGroup.data.push(item);
  return groups;
}, []);

reduce returns the type of whatever is returned from its reducer function. In your case it was an object, and that's why you got an object at the end.
I started with an array and each step I looked in the array to find the related group and push the city into that group's data list.

希望这能帮上忙,祝你好运!

Javascript相关问答推荐

如何在pixi js中画一条简单的线

JavaScript .Click()函数不起作用

为什么有些库公开了执行相同任务的方法,但每个方法都处于同步/同步上下文中?

从外部访问组件变量-Vueejs

如何在JavaScript中通过一次单击即可举办多个活动

使用typeof运算符获取对象值类型-接收字符串而不是数组

序列查找器功能应用默认值而不是读取响应

有Angular 的material .未应用收件箱中的价值变化

警告!合同执行期间遇到错误[执行已恢复](Base Layer 2)

在页面上滚动 timeshift 动垂直滚动条

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

配置WebAssembly/Emscripten本地生成问题

在grafana情节,避免冲突的情节和传说

我在Django中的视图中遇到多值键错误

如何在不影响隐式类型的情况下将类型分配给对象?

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

Webpack在导入前混淆文件名

如何使用JS创建一个明暗功能按钮?

如何在HTMX提示符中设置默认值?

Phaserjs-创建带有层纹理的精灵层以自定义外观