I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys.

private parentArray: {}[] = [
    { Id: 1, Name: 'A' },
    { Id: 2, Name: 'B' },
    { Id: 3, Name: 'C' },
    { Id: 4, Name: 'D' }
  ];

private childArray: {}[] = [
    { Id: 2, parentId: 2, Name: 'a' },
    { Id: 3, parentId: 2, Name: 'b' },
    { Id: 4, parentId: 4, Name: 'c' },
    { Id: 5, parentId: 4, Name: 'd' }
  ];

My goal is to create a new array of nested objects where 'parentId' matches the 'Id' of the parent objects. The desired output should be like this:

private newArray = [
    { Id: 1, Name: 'A', Children: [] },
    {
      Id: 2,
      Name: 'B',
      Children: [
        { Id: 2, parentId: 2, Name: 'a' },
        { Id: 3, parentId: 2, Name: 'b' }
      ]
    },
    {
      Id: 3,
      Name: 'C',
      Children: []
    },
    {
      Id: 4,
      Name: 'D',
      Children: [
        { Id: 4, parentId: 4, Name: 'c' },
        { Id: 5, parentId: 4, Name: 'd' }
      ]
    }
  ];

I've tried using '.intersectionWith([arrays], [comparator])' and '.isMatchWith(object, source, [customizer])' but haven't been able to achieve the desired result. Any help would be greatly appreciated.

Answer №1

One of the easiest methods to achieve this is by using the following code snippet:

const newArray = parentArray.map(
    p => ({ ...p, Children: childArray.filter(c => c.parentId === p.Id) })
)

This will generate the desired output. It's worth noting that while this approach works well, it may not be the most efficient when dealing with large datasets. In such cases, looping over each element in both arrays just once might be a better option (complexity O(𝑝+𝑐), assuming hash lookups are O(1)), like so:

type Parent = typeof parentArray[number];
type Child = typeof childArray[number];
interface New extends Parent {
    Children: Child[];
}

const newArray: New[] = [];
const parentLookup: Record<number, New> = {};    
for (const p of parentArray) {
    const n = { ...p, Children: [] };
    newArray.push(n)
    parentLookup[p.Id] = n;
}
for (const c of childArray) {
    parentLookup[c.parentId]?.Children.push(c);
}
console.log(newArray);

Click Here for Code Playground

Answer №2

type Mother = {
    Id: number,
    Name: string,
}

type Son = Mother & {
    motherId: number;
}

type Family = {
    Children: Son[]
} & Mother


const mothers: Mother[] = [
    { Id: 1, Name: 'Anna' },
    { Id: 2, Name: 'Beth' },
    { Id: 3, Name: 'Clara' },
    { Id: 4, Name: 'Dina' }
  ];

const sons: Son[] = [
    { Id: 2, motherId: 2, Name: 'Alex' },
    { Id: 3, motherId: 2, Name: 'Bob' },
    { Id: 4, motherId: 4, Name: 'Chris' },
    { Id: 5, motherId: 4, Name: 'David' }
  ];

const result = mothers.map((m: Mother): Family => {
    return {
        Id: p.Id,
        Name: p.Name,
        Children: sons.filter((s) => m.Id === s.motherId),
    }
})

console.log(result);

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

Can anyone share best practices for writing unit tests for $scope.broadcast and $scope.$on in Jasmine?

Greetings, I am new to the AngularJs/NodeJs realm, so please bear with me if this question seems basic to some. Essentially, I have two controllers where the first controller broadcasts an 'Id' and the second controller retrieves that Id using $ ...

Comparing time in Angular using variables

I have a time value stored in a variable that I need to compare with another one. Depending on whether my variable is greater than or less than 14:00, I want to display a response. However, I am unsure how to store the "14:00" value in the second variable ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

Guide to setting up a back button to return to the previous page in an iframe application on Facebook

I've developed a Facebook application that is contained within an IFRAME. Upon opening the application, users are presented with the main site, and by clicking on the gallery, they can view a variety of products. The gallery includes subpages that lo ...

Is there a way to access a function or variable from within the scope of $(document)?

Whenever I attempt to utilize this.calculatePrice, it does not work and I am unable to access the external variable minTraveller from within the function. numberSpin(min: number, max: number) { $(document).on('click', '.number-spinner b ...

JavaScript strangeness

I am currently working on a dynamic page loaded with ajax. Here is the code that the ' $.get' jQuery function calls (located in an external HTML page): <script type="text/javascript"> $(function() { $('button').sb_animateBut ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

Working with conditional properties in an AngularJS application across two controllers

Managing Controllers in my Application In my application, I am working with two controllers: Controller 1: When a button is clicked, I open a menu and set the property this.isTelephoneMenuOpen = true;. The result is that the menu opens with options ...

When calling a Vue.js method, it appears to be undefined

Currently, I'm working on developing a Chrome extension using Vue and Browserify. Within my component file, I'm attempting to invoke a method called animateBackground from the mounted hook. However, when checking the console, an error message is ...

Encountering errors preventing the utilization of helpers in fancybox2-rails gem

I've been struggling to implement fancybox2 in my RoR app. I've attempted using the gem and manually adding the files to my assets directory, but I'm having issues with the helpers. Currently, the thumb images generated by the helper are no ...

Share content on Facebook using a single-page application

This inquiry may not be specifically tied to a particular software stack, framework, or coding language. In the current project I'm working on, we are utilizing AngularJS for developing the front-end with a static landing page that loads real data an ...

What could be causing my TypeScript project to only fail in VScode?

After taking a several-week break from my TypeScript-based open-source project, I have returned to fix a bug. However, when running the project in VScode, it suddenly fails and presents legitimate errors that need fixing. What's puzzling is why these ...

How to calculate the difference in months between two dates using JavaScript

Is there a way to calculate the number of months between two dates taking into account specific conditions, such as when the dates are not exact and may have different day counts? Here is an example using the moment library: var date1 = moment('202 ...

Creating a customized store locator using JSON data in WordPress for Google Maps API

I'm currently seeking a customized solution to implement a store locator using the Google Maps API within WordPress. Although there are numerous WordPress plugins available, I prefer a more tailored approach. Here are the specific requirements: ...

Exploring the functionality of surveyjs in conjunction with react and typescript

Does anyone have any code samples showcasing how to integrate Surveyjs with React and TypeScript? I attempted to import it into my project and utilized the code provided in this resource. https://stackblitz.com/edit/surveyjs-react-stackoverflow45544026 H ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

When working with React Native, encountering an issue where passing props using the Map function results in an error stating "undefined is not a function" near the section of code involving the

Hey there! I'm currently facing an issue with fetching data from my Sanity CMS and passing it as props to a child component. Interestingly, the same code worked perfectly on another screen, but here I seem to be encountering an error. Although the dat ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

Should the input field only contain spaces, a validation error will be triggered by the user

I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both ...

Personalize the color scheme for your timeline paper

I am interested in customizing this specific example of a personalized timeline: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Timeline from '@material-ui/lab/Timeline'; import Timeli ...