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

如何动态调取一对多关系关联项?遵循DRY原则实现代码复用

动态生成关联对象的URL(遵循DRY原则)

问题描述

有一个消息对象数组,每个消息通过**一对多(One To Many)**关系关联到user、customer或client中的一个(三者互斥,其余两个字段为null)。需要在不违反DRY(Don't Repeat Yourself)原则的前提下,通过动态处理生成携带对应关联项ID的URL,格式要求如下:

  • 关联user:http://example.com/data/id_user?id=xxx(xxx为实际用户ID)
  • 关联client:http://example.com/data/id_client?id=xxx
  • 关联customer:http://example.com/data/id_customer?id=xxx

用户提供的原始代码示例:

let messages = [{
    "id": 1,
    "title": "quidem molestiae enim",
    "user": {
      id: 4,
      name: 'Alex',
      surnme: 'Rossowell'
    },
    "customer": null,
    "client": null
  },
  {
    "id": 2,
    "title": "sunt qui excepturi placeat culpa",
    "client": {
      id: 7,
      name: 'Andreah',
      surnme: 'Carlos'
    },
    "customer": null,
    "user": null
  },
  {
    "id": 3,
    "title": "omnis laborum odio",
    "customer": {
      id: 2,
      name: 'Maddie',
      surnme: 'Cucurew'
    },
    "user": null,
    "client": null
  },
  {
    "id": 4,
    "title": "non esse culpa molestiae omnis sed optio",
    "user": {
      id: 5,
      name: 'Sophia',
      surnme: 'Riccon'
    },
    "customer": null,
    "client": null
  }
]

messages.map(mess => {
  mess.user && console.log(mess.user.id);
  mess.customer && console.log(mess.customer.id);
  mess.client && console.log(mess.client.id);
})

解决方案

方案1:预定义关联类型列表(易维护)

通过定义所有可能的关联类型数组,动态查找当前消息的有效关联项,避免重复判断逻辑:

const baseUrl = "http://example.com/data";
// 维护所有关联类型,后续新增类型只需修改此数组
const relationTypes = ["user", "customer", "client"];

// 生成所有消息对应的URL数组
const messageUrls = messages.map(message => {
  // 找到当前消息中不为null的关联项类型
  const activeRelation = relationTypes.find(type => message[type] !== null);
  
  // 处理无有效关联的边界情况(根据业务需求调整)
  if (!activeRelation) {
    return null;
  }
  
  const relationId = message[activeRelation].id;
  // 按需求拼接URL,可根据实际格式调整
  return `${baseUrl}/id_${activeRelation}?id=${relationId}`;
});

// 输出结果示例:
// ["http://example.com/data/id_user?id=4", "http://example.com/data/id_client?id=7", ...]
console.log(messageUrls);

方案2:遍历对象属性(无需预定义列表)

通过遍历消息对象的键值对,直接过滤出有效关联项,适合关联类型固定的场景:

const baseUrl = "http://example.com/data";

const messageUrls = messages.map(message => {
  // 遍历消息属性,筛选出目标关联类型且值不为null的项
  const [relationType, relationData] = Object.entries(message).find(
    ([key, value]) => ["user", "customer", "client"].includes(key) && value !== null
  ) || [];
  
  if (!relationType || !relationData) {
    return null;
  }
  
  return `${baseUrl}/id_${relationType}?id=${relationData.id}`;
});

console.log(messageUrls);

两种方案均遵循DRY原则,避免了重复编写mess.user && ...这类判断逻辑,代码更简洁、易维护。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:00:33