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

如何用map合并两个对象数组?仅保留seat_number匹配seatName的项

解决方案

实现思路

  • 先提取seatsArray中的所有座位号存入Set,提升后续座位存在性的判断效率
  • 筛选foodarray,仅保留seatName存在于座位号Set中的项
  • 为每个筛选后的项匹配对应座位对象,合并两者属性生成新对象
  • 收集所有符合条件的合并对象,得到最终数组

代码实现

// 修正原数组的语法错误(补全数组包裹)
const seatsArray = [
    { seat_number: "1K" },
    { seat_number: "2K" },
    { seat_number: "3K"},
    { seat_number: "5K" },
    { seat_number: "6K" },
    { seat_number: "7K" },
    { seat_number: "8K" },
    { seat_number: "9K" },
    { seat_number: "10K" },
    { seat_number: "11K" }
];

const foodarray = [{
  "age": 41,
  "gender": "Woman",
  "holdSeatId": "6417f5440c5374a4d72b4fe6",
  "id": "6417f56a0c5374a4d72b5329",
  "PAXName": "Jianmin Hui",
  "seatName": "22A",
  "seatType": "EC",
  "vip": false,
  "containerId": "6417f5180c5374a4d72b4b63",
  "foodTypeId": "632000e0cdcfde6b6088001a",
  "locationId": "6417f5180c5374a4d72b4b66",
  "orderType": "Pre_Ordered",
  "qty": 1,
  "seatId": "6417f5440c5374a4d72b4fe6"},{
  "age": 44,
  "gender": "Woman",
  "holdSeatId": "63282c0952dba06a20b52d79",
  "id": "6417f56a0c5374a4d72b532b",
  "PAXName": "Pei Li",
  "seatName": "10K",
  "seatType": "BC",
  "vip": false,
  "containerId": "6417f5180c5374a4d72b4b63",
  "foodTypeId": "6295bb887115c2151edef87d",
  "locationId": "6417f5180c5374a4d72b4b71",
  "orderType": "Special_Meal",
  "qty": 1,
  "seatId": "63282c0952dba06a20b52d79",
  "description": "Chicken Noodles",
  "foodCatergoryDescription": "Meal with Meat",
  "fullName": "Chicken Noodles" }];

// 生成座位号集合,用于快速查找
const seatNumberSet = new Set(seatsArray.map(seat => seat.seat_number));

// 筛选并合并数组
const mergedResult = foodarray
  .filter(foodItem => seatNumberSet.has(foodItem.seatName))
  .map(foodItem => {
    // 找到对应的座位对象
    const matchedSeat = seatsArray.find(seat => seat.seat_number === foodItem.seatName);
    // 合并两个对象,若属性冲突,食物对象的属性会覆盖座位对象的
    return { ...matchedSeat, ...foodItem };
  });

console.log(mergedResult);

运行结果

最终数组仅包含seatName匹配seatsArray中座位号的项,输出如下:

[
  {
    seat_number: "10K",
    age: 44,
    gender: "Woman",
    holdSeatId: "63282c0952dba06a20b52d79",
    id: "6417f56a0c5374a4d72b532b",
    PAXName: "Pei Li",
    seatName: "10K",
    seatType: "BC",
    vip: false,
    containerId: "6417f5180c5374a4d72b4b63",
    foodTypeId: "6295bb887115c2151edef87d",
    locationId: "6417f5180c5374a4d72b4b71",
    orderType: "Special_Meal",
    qty: 1,
    seatId: "63282c0952dba06a20b52d79",
    description: "Chicken Noodles",
    foodCatergoryDescription: "Meal with Meat",
    fullName: "Chicken Noodles"
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:02:50