Combining information from two different sources to create a more comprehensive dataset

Two get requests are returning the following data:

[{
  id: 1,
  hId: 2
}, {
  id: 6,
  hId: 1
}]

The second request returns:

[{
  id: 1,
  name: 'Bob'
}, {
  id: 2,
  name: 'Billy'
}, {
  id: 6,
  name: 'John'
}]

The objective using RxJs and observables is to achieve this structure:

[{
  id: 1,
  name: 'Bob',
  married: true // if there's an object with hId equal to id
}, {
  id: 2,
  name: 'Billy',
  married: true // if there's an object with hId equal to id
}, {
  id: 6,
  name: 'John',
  married: false 
}]

The current approach involves using forkJoin, but it requires iterating over responses[0] within map and filtering/searching for elements within subjects. Is there a more efficient way to achieve this using one of the rxjs operators/functions?

const joint = forkJoin([mariage, subjects]);
  return joint.pipe(
    map(responses => {
      responses[0].data.forEach((mItem) => {
        const found = responses[1].data.find((subj) => {
          return subj.id === mItem.hId;
        });
        mItem.married = found ? true : false;
      });
      console.log(responses[0].data);
      return responses[0].data;
    })
  );

Answer №1

Regrettably, there is no miraculous rxjs operator that executes a matching algorithm on arrays. The issue you are facing does not directly involve observables. However, you might enhance the brevity of your code by utilizing destructuring and mapping when transforming your array:

forkJoin([courses, students]).pipe(
  map( ([ courseData, studentData])  => 
    courseData.data.map((cItem) => ({
      ...cItem,
      enrolled: studentData.data.some(item => item.courseId === cItem.id)
    })
  ))
)

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

Mastering the Type Model on Firestore Function to Retrieve Field ValuesUnlock the potential of the Type

When retrieving data from Firestore, I am able to print the entire object using doc.data. However, I am having trouble accessing the specific value of unixtime as it is coming through as undefined. I need help in correctly applying my type model so that I ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Leverage the power of zustand actions in your axios queries!

In my React application, I have implemented Zustand for creating a store: import { create } from 'zustand'; interface IAuth { username: string; isAuthentificated: boolean; updateAuth: (isAuth: boolean) => void; } export const useAuth = ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

Is there a way to both add a property and extend an interface or type simultaneously, without resorting to using ts-ignore or casting with "as"?

In my quest to enhance an HTMLElement, I am aiming to introduce a new property to it. type HTMLElementWeighted = HTMLElement & {weight : number} function convertElementToWeighted(element : HTMLElement, weight : number) : HTMLElementWeighted { elemen ...

How can I showcase the captured image on Ionic 2?

I am having trouble displaying the selected or captured image on the page after uploading it through two methods - one using the gallery and the other using the camera. ** Here is my code ** 1) profile.html: <img class="profile-picture" src="{{baseUr ...

Running cypress tests with regression or smoke tags within nx workspace is a straightforward process

I have a cypress project set up and I am trying to run cypress tests based on tags using the nx command. cypress grep--->"@cypress/grep": "^4.0.1" After applying the nx command like this: nx run e2e:e2e --tags=@regression The issu ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

The classification of rejected promises in Typescript

Is it possible to set the type of rejection for a promise? For example: const start = (): Promise<string> => { return new Promise((resolve, reject) => { if (someCondition) { resolve('correct!'); } else { ...

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

When using AWS/Cognito and setting up a user pool with CDK, is there a way to specify the character limits for standard attributes? Specifically, I would like to establish a minimum and maximum

When setting up a user pool in AWS/Cognito using CDK, how can I specify the string length for standard attributes? I've been trying to figure this out but haven't had any luck so far. I'm working with Typescript. This is how my user pool i ...

When attempting to send an email with nodemailer, an error message popped up saying "setImmediate is not defined."

let transporter = nodemailer.createTransport({ host: "sandbox.smtp.mailtrap.io", port: 2525, auth: { user: "xxxxxx", pass: "xxxxxx" }, tls: { rejectUnauthorized: false } ...

Guide on incorporating a bespoke cordova plugin into your Ionic 4 project

After successfully completing all the necessary steps to create a new Cordova plugin as outlined in the link below: Start android activity from cordova plugin I executed the command cordova plugin ls which returned the following result: com.example.sam ...

The error TS2304 in @angular/common is indicating that the name 'unknown' cannot be found

I am struggling to revive an old project due to some errors. I am using Angular 5.2.9 for the build, but these errors keep popping up. If anyone can offer assistance, I would greatly appreciate it. This is how my package.json file appears: "dependencies" ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...