You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配数组外键并统计对应出现次数,生成目标结构新数组?

实现方法

步骤1:统计各城市对应的地点数量

先创建一个临时对象,用来记录每个城市ID对应的地点总数,遍历list_places数组,对每个fk_city的计数进行累加:

// 初始化统计对象
const placeCountMap = {};
list_places.forEach(place => {
  const cityId = place.fk_city;
  // 已存在则计数+1,不存在则初始化为1
  placeCountMap[cityId] = (placeCountMap[cityId] || 0) + 1;
});

步骤2:关联城市列表生成目标数组

遍历list_cities数组,结合统计结果生成要求的结构:

const result = list_cities.map(city => {
  // 取对应ID的数量,无匹配则为0,转成字符串格式
  const count = placeCountMap[city.$id] || 0;
  return {
    city: city.name,
    places: count.toString()
  };
});

完整示例(含测试数据)

假设原始数据如下:

const list_cities = [
  { $id: 1, name: "Pittsburg" },
  { $id: 2, name: "Los Angeles" },
  { $id: 3, name: "New York" }
];

const list_places = [
  { fk_city: 1, name: "Place A" },
  { fk_city: 1, name: "Place B" },
  { fk_city: 2, name: "Place C" }
];

运行代码后,result输出为:

[
  { city: "Pittsburg", places: "2" },
  { city: "Los Angeles", places: "1" },
  { city: "New York", places: "0" }
]

如果不需要显示地点数为0的城市,可在map后追加过滤逻辑:

const result = list_cities
  .map(city => {
    const count = placeCountMap[city.$id] || 0;
    return {
      city: city.name,
      places: count.toString()
    };
  })
  .filter(item => item.places !== "0");

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:15:45