Establish a connection between two JSON files using the WordPress REST API

I have developed an app using ionic 2 that revolves around quotes. My goal is to manage these quotes (along with authors, categories, etc) using Wordpress and its REST API. Initially, I utilized normal posts for this purpose, but now I am exploring custom post types as they offer more control and organization in the backend. This led me to create one CPT for quotes and another for authors, establishing a relationship between them.

For example:

wp-json/wp/v2/quotes

[
  {
    id: 79,
    x_metadata: {
      custom_post_type_onomies_relationship: "77",
      quote: "Be yourself; everyone else is already taken"
    }
  }
]

wp-json/wp/v2/authors

[
  {
    id: 77,
    title: {
      rendered: "Oscar Wilde"
    },
    x_metadata: {
      bio: "https://wikipedia.org/wiki/Oscar_Wilde"
    }
  }
]

In the above example, you can see that the relation is defined by

custom_post_type_onomies_relationship
, but I am unsure of how to properly merge this data within the app (where Angular 2/Typescript is used).

The only solution that comes to mind is to loop through the quotes, then for each quote, loop through authors to check their IDs, and finally add the author's data into the quotes array. Is this approach acceptable or is there a more efficient method available?

Thank you in advance and please forgive any imperfections in my English.

Answer №1

If you need information on authors, try using the _embed request.

wp-json/wp/v2/quotes?_embed=

Explore embedding options here

Up-to-date Information

Keep in mind that embedded resources are only accessible for specific fields such as post authors and replies.

A possible solution is to loop through quotes and for each quote, go through the authors to match ids and include author data within the quotes array.

If you require linked data that isn't directly embeddable, a common approach to minimize REST API calls is to fetch all authors initially and create an array map of author_id to authors stored on the client side.

  • Performance of nested loops is O(n^2)
  • Looping through quotes and conducting indexed searches (authors[id] or Array.indexOf) results in a performance of O(n*logn)

For further insights on array search efficiency in JavaScript, refer to this discussion.

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

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

Creating an efficient post request using retrofit

Currently, I am delving into the world of Retrofit as it appears to provide solutions to many of the challenges I face with JSON requests and their handling. It is clear that interfaces play a key role in defining the methods utilized, particularly when m ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

Tips for effectively transmitting data while utilizing a declarative/reactive data access method with RxJS in Angular?

Angular typically follows a classic pattern for data access that looks like this: Traditional Data Access Pattern getProducts(): Observable<Product[]> { return this.http.get<Product[]>(this.productsUrl) .pipe( tap(data => consol ...

Determine the output type of a function in Typescript using an input value specified by an enum

I am currently saving settings to local storage and want to be able to input responses when retrieving (and possibly inserting) values from/to the storage. After researching, it seems that using function overloading is the best approach. Here is what I ha ...

Converting Basic JSON Data into an SQL SELECT Query

Presented is the subsequent JSON data: DECLARE @json NVARCHAR(MAX) SET @json = N'[ {"@odata.context":"http://www.example.com","value":[ {"financialmovements_ID":1,"Data":"2020-02-10T00:00:00Z","ES":"E","Descri\u00e7\u00e3o":"FIV-005 3& ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

"Unlocking the potential of RavenDB 4.0 with raw json data storage

Currently, I am utilizing NLOG for logging purposes with the JsonLayout and my goal is to save these logs in RavenDB 4.0. Essentially, I am attempting to store raw JSON data into RavenDB using the RavenDB .NET client. In the past, I had a functioning solu ...

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

When employing the caret symbol (^) in package.json, it fails to update the minor version

Within my package.json file, there is a line that reads as follows: "typescript": "^4.1.6", The presence of the caret (^) symbol indicates that npm should install a version of TypeScript above 4.1 if available. However, upon checking ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Tips for parsing text responses in React to generate hyperlinks and emphasize specific words

I'm currently tackling a React project and facing an interesting challenge. I have a text response that needs to be parsed in a way that all URLs are automatically turned into clickable hyperlinks (using anchor tags). Moreover, there's a requirem ...

Enhance the current menu item in WordPress by assigning a class to the anchor tag

function updateActiveClassOnMenu($item_output, $item, $depth, $args) { $menu_locations = get_nav_menu_locations(); if ($item->menu_order == 1){ $item_output = preg_replace('/<a /', '<a class="active" ', $item_o ...

I am unable to generate an Angular file

PS D:\AngularCalismalar> ng new intro Node.js version v17.1.0 was detected. It is recommended not to use odd numbered Node.js versions for production as they will not enter LTS status. For more information, visit https://nodejs.org/en/about/relea ...

Error: Unexpected input detected in `ts.resolveTypeReferenceDirective`. This issue may lead to a debug failure

I'm encountering the error below: { "name": "Angular", "version": "1.0.0", ... } If anyone has insights on what steps to take next or the potential cause of the problem, your input would be greatly a ...

Quickly retrieve product categories associated with products using GraphQL in WordPress through WPGraphQL

Currently, I am working on a headless eCommerce solution using Wordpress, Woocommerce, WooGraphQL, React, and Next. I am implementing SSG and SSR for improved SEO and performance. One area of concern for me is the performance impact of populating product ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked: $http({ url: 'default.aspx/G ...