Is there a way to dynamically retrieve the linked item in a One to Many relationship?

In my array of objects, each message is connected to either a user, a customer, or a client through a One To Many relationship:

What I want to explore is the possibility of using a variable to make the code dynamic without violating the DRY principle.

The example provided is a console.log, but what is actually needed is a link that only requires the ID of the messages related to a specific item in order to display other relevant data.

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

The URL structure will be as follows:

If related to user: http:\....data\id_user

If related to client: http:\....data\id_client

If related to customer: http:\....data\id_customer

Any help on this matter would be greatly appreciated.

Answer №1

When detecting a populated property, I may opt for using optional chaining.

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
  },
  {
    "id": 5,
    "title": "non esse culpa molestiae omnis sed optio",
    "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 ? id : 'not found');
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Set up a global configuration for all $.ajax calls to enable automatic retries in case of a timeout

Looking for a solution to implement a global timeout function using $.ajaxSetup in my Phonegap app. The goal is to automatically retry ajax GET or POST requests in case of timeout, specifically due to poor internet connection. As a Backbone.js user, I hav ...

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...

Improved way to handle nested if statements in JavaScript

Suppose there exist 3 divs within my HTML document with the following IDs: stepone steptwo stepthree The objective is to first fetch JSON data from the server and load it into the stepone div. If the returned status is '1', then display ' ...

When angular directives fail to function properly when added dynamically

Could someone please help me understand why the directive below is not being called? It works when I directly add the directive to the button. I even tried adding it using $timeout but still no luck. <html> <head> < ...

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

Using Regex to detect recurrent (similar) patterns in jQuery <input> tags

I need assistance with ensuring that users input article numbers in the correct format, like this: ABC_ABC123; AB__B2A4; ABF_323WET; ... Currently, I have a regex pattern that works for one article number: var mask1 = /^([A-Z]{2})([A-Z|_]{1})_([A-Z0-9]{ ...

Error: React JS is unable to access the property 'path' because it is undefined

Currently, I am encountering an issue while setting the src of my image in React to this.props.file[0].path. The problem arises because this state has not been set yet, resulting in a TypeError: Cannot read property 'path' of undefined. To provid ...

Issue encountered while transferring SQL Server data to user interface

Hello and I hope you're having a great day :). Currently, I am working on pulling data from SQL server to my react project. I have successfully retrieved the data in json format to be displayed on localhost:5000 (where my server.js is running). I hav ...

React is throwing an error because a unique key is missing for the map iteration

I'm encountering an issue with missing a key prop in my map iteration. I have nested maps and can't figure out where the missing key is located. Could someone please assist me? displayData() { const { data, index } = this.state; let sortedDa ...

Google Cloud Endpoints API Encounter 404 Error

Scenario Currently, my setup involves AppEngine Cloud Endpoints using a Bootstrap JavaScript UI along with a Google SQL Datastore. Issue The problem arises when the Javascript tries to call gapi.client.load and receives a 404 error. Surprisingly, the ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Library for JavaScript coding within a textarea element, complete with correct indentation

Seeking a JavaScript library for coding in a textarea with proper indentation. Came across Behave.js () which lacks the basic feature of indenting a new line based on the last lines indent. It only auto-indents by recognizing braces and parentheses. Codem ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

From jQuery to ReactJS: Migrating to a Modern

As I venture into converting existing jQuery code to React.js, I must admit that I am quite new to React and still in the learning phase. So please bear with me if my questions sound a bit silly. Here is the structure I am working with: <ul> &l ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...

What is the best way to update comments after submitting an AJAX request?

I stumbled upon a lightweight script that allows for submitting WordPress comments via AJAX. Although the comments are successfully submitted, the new comment does not appear immediately; only the comment count gets updated. Upon manually refreshing the pa ...