Combine two arrays of objects using the lodash library

I am working with two arrays of objects named films and filmDetails:

const films = [{
        filmID: 0,
        filmDetailsID: 9,
        filmName: "Avatar",
        price: 12
    },
    {
        filmID: 1,
        filmDetailsID: 10,
        filmName: "Inception",
        price: 18
    },
    {
        filmID: 2,
        filmDetailsID: 11,
        filmName: "The Dark Knight",
        price: 25
    }
];

const filmDetails = [{
        filmDetailsID: 10,
        actor: "Leonardo DiCaprio",
        fee: 150
    },
    {
        filmDetailsID: 10,
        actor: "Tom Hardy",
        fee: 170
    },
    {
        filmDetailsID: 11,
        actor: "Christian Bale",
        fee: 250
    }
];
  1. I am looking to combine these two sets of objects by matching the filmDetailsID. I am considering using lodash for this task.
  2. In my final output, I want to select specific attributes from both films and film details. For films, I only want to include film name and price, while for film details, I need actor and fee.

Expected Result:

 {
    filmID: 0,
    filmDetailsID: 9,
    filmName: "Avatar",
    price: 12
}, {
    filmID: 1,
    filmDetailsID: 10,
    filmName: "Inception",
    price: 15,
    details: [{
            filmDetailsID: 10,
            actor: "Leonardo DiCaprio",
            fee: 150
        },
        {
            filmDetailsID: 10,
            actor: "Tom Hardy",
            fee: 170
        }
    ]
}, {
    filmID: 2,
    filmDetailsID: 11,
    filmName: "The Dark Knight",
    price: 25,
    details: [{
        filmDetailsID: 11,
        actor: "Christian Bale",
        fee: 250
    }]
}

My Attempt . However, my current approach merges the data without creating a separate 'details' object for adding matching film details IDs.

var mergedData = _.map(films, function(item){
        return _.extend(item, _.findWhere(filmDetails, { filmDetailsID: item.filmDetailsID }));
      });

Answer №1

Behold, a straightforward solution using lodash

import groupBy from "lodash/groupBy";
import reduce from "lodash/reduce";

const finalResult = reduce(films, ([filmDetailsIndex, result], film) => [
  filmDetailsIndex,
  [...result, {...film, ...(filmDetailsIndex[film.filmDetailsID] ?
    {details: filmDetailsIndex[film.filmDetailsID]} : {}
  )}]
], [groupBy(filmDetails, "filmDetailsID"), []])[1];

Answer №2

If I have grasped everything correctly, here is a pure JavaScript solution:

const films = [
  {
    filmID: 0,
    filmDetailsID: 9,
    filmName: "Star Wars",
    cost: 12
  },
  {
    filmID: 1,
    filmDetailsID: 10,
    filmName: "The Matrix",
    cost: 18
  },
  {
    filmID: 2,
    filmDetailsID: 11,
    filmName: "Inception",
    cost: 25
  }
];

const filmDetails = [
  {
    filmDetailsID: 10,
    actor: "Keanu Reeves",
    payment: 150
  },
  {
    filmDetailsID: 10,
    actor: "Carrie-Anne Moss",
    payment: 120
  },
  {
    filmDetailsID: 11,
    actor: "Leonardo DiCaprio",
    payment: 250
  }
];

const outcome = films.map(film => {
  const details = filmDetails.filter(fd => fd.filmDetailsID === film.filmDetailsID);

  const { filmID, filmDetailsID, ...filmKeys } = film;
  
  const filteredFilm = { ...filmKeys };
  
  if (details.length) {
    const filteredDetails = details.map(({
      filmDetailsID,
      ...keys
    }) => keys);

    return ({
        ...filteredFilm,
        details: filteredDetails,
    });
  }

  return filteredFilm;
});

console.log(outcome);

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

Navigating through Firebase after login

Encountering an issue with navigating to the register page using a firebase authentication promise. Instead of displaying only the register page, both the login page and register page are shown simultaneously: Login page with social buttons Register page ...

Transforming arrays with map or alternative methods in javascript

Below is the JSON object I am working with: { id: 3, cno: 103, username: 'basha', name: 'New Complaint', desc: 'Need bag', storeId: [ 5, 1 ] } My desired output should look like this: [ {id: 3,cno: 103, ...

Leveraging jQuery across multiple angular.json configurations and modules within an Angular application

Currently, I have a template that utilizes jQuery in various sections. In my angular.json file, I specify the following scripts: "scripts": [ "node_modules/jquery/dist/jquery.js", "src/assets/vendor/slimscroll/slimscroll.min.js", ] This setup works s ...

php preg_replace function that utilizes the original value

Trying to iterate through a dataset in My SQL and automatically update JSON strings with an object member set as an integer instead of a string is my current goal. I am seeking the quickest and simplest solution, which has led me to utilize regex. The ide ...

I am experiencing an issue where my 3D object (JSON file) is not loading properly within my 3D scene

I'm experiencing some issues with loading my 3D object (json file) into my 3D scene. Could it be that I haven't fully integrated my property yet? I also haven't assigned any textures to it. The model was created in Blender using the three ...

Switching ng-loading from a different component

I am currently utilizing ngx-loading and I would like to have the ability to control its visibility from child components. This is my current setup: Main Component import { Component, Injectable } from '@angular/core'; @Injectable() export cla ...

Developing a front-end Angular application with a back-end C# API to handle posting of form data, including files

Seeking assistance with understanding how to upload a file (FormData) and an object from Angular to C# API. It seems that the HttpClient post method can only accept one body parameter, so I am unable to post both the FormData object and the SomeObject obje ...

What is the potential return type for a List of JSON objects in Angular 2 using TypeScript?

What could be the possible return type of the getFiles() function other than 'any'? Is there a specific return type that can be used? @Injectable() export class NodeService { constructor(private http: Http) {} getFiles() { retu ...

How can one stop PHP warnings and errors from disrupting the JSON parser?

I have a PHP script that retrieves a record from a database and returns a JSON object. The script includes error handling to ensure that even if an exception is thrown or other errors occur, it still provides a properly formatted JSON response with an erro ...

Implementing a searchable drop-down in AngularWould you like to learn how

I'm struggling with adding search functionality to my dynamic dropdown. If anyone could assist me in implementing the search feature, I would greatly appreciate it. I have successfully created a dropdown with search for static data but am facing chall ...

Displaying user information in the header section of an Angular app

I am trying to incorporate user avatars in the header of my Angular 2+ application. The avatar data is retrieved from a JWT token that is decoded within a user service. However, when I try to display the avatar in my HeaderComponent, it always appears as u ...

Navigating the root path that is defined in the gulp task within an Angular application

My current task involves building my application with the following code: const app = new Metalsmith(config.styleguide.path.root); app.use( msDefine({ production: false, rootPath: '/' }) ); app.use( ms ...

Creating JSON output in Spark with an array of objects

How can I transform the JSON structure using a Spark process to output an array of objects? My input file consists of the following lines: { "keyvals" : [[1,"a"], [2, "b"]] }, { "keyvals" : [[3,"c"], [4, "d"]] } The desired output format should be: { " ...

Encountering the error 'unterminated object at' while attempting to retrieve the value of a specific key from a JSON file

Below is the structure of the JSON: {userModel={name=Mark Kohl Mundi, photo_profile=***}, message=hi, timeStamp=1510326004316, newMsgIndicator=0} Here is how I am attempting to parse it: for (DataSnapshot childrenSnapshot: dataSnapshot.getChildren()) { ...

I am facing difficulty in retrieving data from Firestore using Angular

I've been utilizing the AngularFireList provided by @angular/fire/database to retrieve data from firestore. However, despite having data in the firestore, I am unable to fetch any information from it. import { Injectable } from '@angular/core&apo ...

Growing Pandas Dataframe Column Using JSON Structure

I am in search of a clean and efficient method to expand a pandas dataframe column that contains a JSON object (essentially a dictionary of nested dictionaries). The objective is to create one column for each element in the JSON column in normalized form, ...

Putting a | in the navigation bar

Could use some assistance here as I'm struggling to add a | between 'About Us' and 'Login' in my code. Any tips on how to achieve this? I've checked other posts but can't seem to apply it correctly to my specific lines of ...

The parameter cannot be assigned to type 'HTMLCanvasElement | null' due to conflicting arguments

I am encountering an issue with the following code, as it fails to compile: import React, {useEffect} from 'react' import {Card, Image} from 'semantic-ui-react' import * as chart from 'chart.js' export const PieChartCard = ...

What is the significance of the error message "Surprisingly in Angular Zone despite expectations"?

Ever since upgrading from Angular 2 RC4 to RC5, I've been encountering this error. Although it doesn't seem to impact the application's functionality, it keeps appearing in the console and may draw attention away from other errors. Does any ...

What is the reason for web2py json services not handling lists correctly?

When dealing with JSON that has an outermost container as an object like { ... }, the following code snippet works: @service.json def index(): data = request.vars #fields are now accessible via data["fieldname"] or data.fieldname #processing m ...