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

Node.js中不覆盖数据合并两个数组的实现方案求助

问题描述

需要将从数据库获取的两个places数组合并为一个,且不覆盖原有数据。尝试过lodash的merge、concatenate等方法但未成功。

原始数组示例

第一个数组:

places: [
    { placeId: 2, place: 'a' },
    { placeId: 3, place: 'b' },
    { placeId: 4, place: 'c' },
    { placeId: 5, place: 'd' },
    { placeId: 6, place: 'e' }
  ]

第二个数组:

places: [
    { placeId: 12, place: 'f' },
    { placeId: 13, place: 'g' },
    { placeId: 14, place: 'h' },
    { placeId: 21, place: 'i' },
    { placeId: 22, place: 'j' },
    { placeId: 29, place: 'k' },
    { placeId: 30, place: 'l' }
  ]

期望合并结果

places:[
    { placeId: 2, place: 'a' },
    { placeId: 3, place: 'b' },
    { placeId: 4, place: 'c' },
    { placeId: 5, place: 'd' },
    { placeId: 6, place: 'e' },
    { placeId: 12, place: 'f' },
    { placeId: 13, place: 'g' },
    { placeId: 14, place: 'h' },
    { placeId: 21, place: 'i' },
    { placeId: 22, place: 'j' },
    { placeId: 29, place: 'k' },
    { placeId: 30, place: 'l' }
]
解决方案

原生JavaScript实现

你的两个数组没有重复placeId元素,直接用concat就能完成合并:

const places1 = [/* 第一个数组内容 */];
const places2 = [/* 第二个数组内容 */];
const mergedPlaces = places1.concat(places2);

或者用扩展运算符,写法更简洁:

const mergedPlaces = [...places1, ...places2];

Lodash实现

你之前用merge是错的,merge是用来合并对象的,不是数组。Lodash里可以用concat方法:

const _ = require('lodash');
const mergedPlaces = _.concat(places1, places2);

或者用flatten展开包含两个数组的数组:

const mergedPlaces = _.flatten([places1, places2]);

额外:如果数组存在重复placeId需去重

如果后续可能出现相同placeId的元素,要保留唯一值的话,可以用下面的方法:

原生JS:

const mergedPlaces = Array.from(
  new Map([...places1, ...places2].map(item => [item.placeId, item])).values()
);

Lodash:

const mergedPlaces = _.uniqBy([...places1, ...places2], 'placeId');

内容的提问来源于stack exchange,提问作者Josip Marić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37