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

如何合并两个数组并按属性过滤 移除Name匹配的IsDirector为null的对象

实现方案

你的思路是对的,结合数组合并和过滤即可实现需求。核心逻辑如下:先把profile数组里的所有国家名称存储下来,再过滤掉countries数组里名称重复的项(这些重复项的IsDirector固定为null,符合要移除的规则),最后合并两个数组即可。

完整实现代码

let profile = [
   {
      "IsDirector":true,
      "Name":"Germany"
   },
   {
      "IsDirector":false,
      "Name":"Spain"
   },
]

let countries = [
   {
      "IsDirector":null,
      "Name":"Germany"
   },
   {
      "IsDirector":null,
      "Name":"Spain"
   },
   {
      "IsDirector":null,
      "Name":"Portugal"
   }
]

// 收集profile数组中所有的Name值
const profileNameSet = new Set(profile.map(item => item.Name))
// 过滤countries数组,只保留Name不在profile里的项
const validCountries = countries.filter(item => !profileNameSet.has(item.Name))
// 合并两个数组得到最终结果
const result = [...profile, ...validCountries]

console.log(result)

输出结果

运行代码后得到的结果和期望输出完全一致:

[
  { IsDirector: true, Name: 'Germany' },
  { IsDirector: false, Name: 'Spain' },
  { IsDirector: null, Name: 'Portugal' }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:36:01