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

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

What is the best method for linking JavaScript to Python while exchanging data in JSON format bidirectionally?

I am currently exploring methods to establish a local connection between a Python server and a Javascript client by utilizing JSON format for the retrieval of data. Specifically, I aim to execute queries on the HTML client side, transmit these queries to t ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

Guard against an array that contains different data types

I am trying to create a guard that ensures each entry in an array of loaders, which can be either query or proxy, is in the "success" state. Here is my attempted solution: type LoadedQueryResult = Extract<UseQueryResult, { status: 'success' }& ...

How can I develop a REST API in Python that utilizes JSON?

As a newcomer to Python REST API, I am encountering some specific issues. My goal is to retrieve the data associated with a particular key (pathlabid) when it is entered as input. However, upon running the code below, I am only able to fetch data from th ...

Calculate the total sum of an array in Angular based on a specific condition of another key

How do I calculate the sum of array elements where sel1, sel2, or sel3 is equal to 1 from the following Array? [ { "sel1": 0, "sel2": 1, "sel3": 0, "price": 10 }, { "sel1": 0, "sel2": 1, &qu ...

React: Dealing with unsuccessful imports

Whenever a device loses internet connection, my app crashes due to an imported component that relies on Google Maps. To address this issue and prevent the app from showing a blank screen, I want to intercept the failed Google Maps import and display an err ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

Retrieve data from a function in PHP while being outside of it

Embarking on this new journey of creating a plugin in wordpress, I find myself faced with the task of integrating jQuery code into my footer. The function at the beginning of my document serves this purpose, and here is a simplified version: function slug ...

Unraveling the Mystery of JSON Objects in PHP

Here is the format of my JSON data : { "amount":550, "items":[ {"item_id":12334, "price": 504}, {"item_id":12335, "price":206} ] } Can someone guide me on how to properly parse this data so that I can retrieve each piece of information in in ...

Redirecting based on conditions in Angular 2+ with wildcard paths

I have a variety of paths, each corresponding to a specific stage in a wizard. const routes: Routes = [ { path: ':id', component: ParentComponent, children: [ {path: 'step1', component: Step1Component}, {path: ...

How can I access each element of the array in Java within Android Studio?

When I receive an array of strings in the responseJSON like this: Result: responseJSON = ["Product1","Product2","Product1","Product2"] try { // Invoke web service androidHttpTransport.call(SOAP_ACTION+methName, envelope); // Get t ...

The Angular application has encountered a stack overflow due to exceeding the maximum

./src/main.ts - An issue occurred: The module build process failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js): Error: Maximum call stack size exceeded import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; { App ...

Accessing an API Gateway without relying on Ajax calls - Tips for formatting JSON

I have primarily relied on ajax calls for making API requests in the past. However, I now have a requirement from a client to assist them in programmatically hitting an AWS API Gateway. Despite my efforts to research the necessary data to send to the invok ...

Unable to retrieve values from nested objects in component.html

Hey fellow tech enthusiasts, I'm currently dealing with a complex nested JSON object retrieved from an API. Here's a snippet of the object: profile : { title:"Mr", personalInfo:{ fullNames: "John Doe", id ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

Enhance your Select options using Ajax and Jquery by updating based on the value of another Select option

I'm struggling to understand how to dynamically update the options in a second select box based on the selection made in the first one. To achieve this, I am aiming to utilize a predetermined JSON object for the available choices in the second select ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...