如何动态调用与一对多关系关联的项目?

问题描述 投票:0回答:1

我有一个对象数组,其中每条消息都通过一对多关系与用户、与客户、与客户相关:

我想了解的是,是否有可能在不重复代码的情况下,在不违反 DRY 原则的情况下,使用变量使一切变得动态。

下面的例子是一个console.log,但显然需要的不是这个,而是一个仅获取与特定项目相关的那些消息的ID来打印其他相应数据的链接。

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);
})

网址将是这样的:

如果与用户相关: http:\....data\id_user

如果与客户相关: http:\....data\id_client

如果与客户相关: http:\....data\id_customer

有人可以帮助我吗?

javascript json response relation
1个回答
0
投票

我可能会使用可选链来检测填充的属性。

const id = mess.user?.id || mess.customer?.id || mess.client?.id;

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 => {
  console.log('Message: ', mess.id);
  const id = mess.user?.id || mess.customer?.id || mess.client?.id;
  console.log('Id: ', id);
})

© www.soinside.com 2019 - 2024. All rights reserved.