merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects:

vehicles: [
{
  vId: 1,
  color: 'green',
  passengers: [
    {
      name: 'Joe',
      age: 22
    },
    {
      name: 'Jack',
      age: 32
    }
  ]
}
more vehicles....]



pDetails: [
  {
    vId: 1,
    detail: tall
  },
  {
    vId: 1,
    detail: 'fat'
  },
  { 
    vId 2,
    detail: 'sad'
  } more details.....
]

If the vIds in both objects match, I want to merge pDetails into a new array within the corresponding vehicle object in the vehicles array. My project is built using Angular 5 and Typescript with Lodash integrated. I am struggling with iterating through nested arrays as I am still fairly new to JavaScript and not completely familiar with its APIs. Are there any features in TypeScript, ES6, Angular, or Lodash that could simplify this process for me?

Here is what I have managed to achieve so far:

this.getVehicles().subscribe(
      data => { v = data.result.objects },
      err => console.error(err),
      () => Object.keys(v).forEach(key => {
      console.log(v[key]); //mapping logic here
    })

While this successfully loops through the vehicles array, my goal is to iterate through each passenger object within each vehicle and search for matches in the pDetails array, copy them, push them into a temporary array, and then assign them to the passengers array of the respective vehicle. I am still struggling to understand how to iterate through each vehicle's passenger array.

Answer №1

Utilizing the powerful rxjs functions can prove to be beneficial when dealing with such issues.

Here is a suggested code snippet for retrieving vehicles with detailed information using combineLatest (please note that this code is for demonstration purposes and has not been tested) :

// The initial value pushed will be
// an array of values pushed by the Observables
combineLatest(this.getVehiclesDetails(),this.getVehicles())
.pipe(
    // By utilizing the returned values, you can customize them as needed
    map(([vehicles, details]) =>
        // Transforming our vehicles array into vehiclesWithDetail array
        vehicles.map(vehicle => {
            // Retrieving details for the current vehicle
            const detail = details.find(d => d.vdId == vehicle.vdId);
            // Merging the two objects into one
            return Object.Assign(vehicle, detail);
        })
    )
)

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

Troubleshooting the issue of AJAX not successfully transmitting variables to PHP

let xmlhttpRequest; if (window.XMLHttpRequest) { xmlhttpRequest = new XMLHttpRequest(); } else { xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttpRequest.open("POST", "test.php", true); xmlhttpRequest.setRequestHeader("Content-typ ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

transferring scoped model information to the controller

When using AngularJS, my view is structured like this: <div class="sli1" ng-init="values=[10,20,30,40,50]" <div class="sli2" ng-init="values2=[10,20,30,40,50]" I am attempting to send the initial data models back to the controller for retrieva ...

Use JavaScript to load and set a background image for a div

When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that. $(window).load(function() { var randomImages = [&apo ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

"Encountered an Unspecified Variable Error in executing document

Every time I open my Chrome console, it keeps showing an error message saying "toggleOnlyRelatedPosts is not defined". The script I'm working on doesn't seem to be functioning properly. I've added so many variables that I now feel lost and o ...

Updating pointers to elements depending on their current status

I am working with an array and looping through it to create div elements. Depending on whether the divs are 'active' (determined by state), I want to assign them the ref property. The ref is also the parameter for a hook that adds an onclick list ...

Is there a way for me to set distinct values for the input box using my color picker?

I have two different input boxes with unique ids and two different color picker palettes. My goal is to allow the user to select a color from each palette and have that color display in the corresponding input box. Currently, this functionality is partiall ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

Utilizing @ngrx/router-store in a feature module: A comprehensive guide

The NGRX documentation for Router-Store only showcases an example with .forRoot(). Upon experimenting with .forFeature(), I realized that this static method does not exist. I am interested in defining certain actions and effects to be utilized within my f ...

Value is not defined when subscribing to subject in Event Bus Implementation

After creating an EventBusService and EventData, here is the implementation: export class EventData { public eventName: string; public event: any; constructor(eventName: string, event: any) { this.eventName = eventName; this.e ...

Using Vue JS to handle image upload with "PROP MUTATING"

Apologies for any language barriers or inaccuracies in my English. I have a single component designed specifically for image uploads. It is currently being utilized in two forms: an add form and an edit form. In the edit modal, the Image URL is passed as ...

Adjusting the dimensions of a tri-fiber canvas prior to saving it

I have a unique inquiry regarding Three Fiber. Once the download button is clicked, it generates a base64 using toDataURL, which can then be downloaded. The resulting image adopts the height and width of the canvas, which in turn matches the height and w ...

The issue is that only the first checkbox within ngFor is being toggled on and off each time a different checkbox is clicked

When I have checkboxes inside a ngFor loop and click on any one of them, only the first one gets checked and unchecked, updating only the status of the first checkbox. Here is the HTML template: <div *ngFor="let num of count" class="m-b-20"> & ...

Effortlessly Transition to Full Screen with Div Expansion on Click

I'm currently working on creating a smooth transition for a div to expand fullscreen when clicked. My goal is to achieve a similar effect as the case studies on this website: Although my code can make the div go fullscreen, there's an issue with ...

Launch a new window for a div when a button is clicked

Hey everyone, I need some help with opening a div in a new window. Currently, I am using window.open and it is working fine. Here is the code snippet: <div id="pass">pass this to the new window</div> <a href="#" onclick="openWin()">clic ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Bootstrap 4 - DropDown option - Element is positioned above the navigation bar

Currently facing an issue with the DropDown menu. Whenever I add padding to the DropDown menu (class - drop_link), it ends up pushing the entire element over the <nav>. I'm unsure of how to prevent this from occurring. I attempted to disable som ...

Ways to restrict a JavaScript object from being sent through ajax requests

I have developed an application that utilizes JSON to send messages through ajax. Here is the JavaScript object used for this purpose: var message = { "message_by": colmn[0].innerHTML, "message_date": new Date(), "message_recipients": [ { ...

How should white space be managed in Bootstrap 4 cards when incorporating responsive column classes - wrap elements inside divs or apply classes directly?

In Bootstrap 4, when applying a responsive column class like "col-sm-8" directly to a "div" with the class "card", whitespace is added between the card border and content. This can be seen in the highlighted yellow area in the image below. https://i.sstat ...