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

The requested function is nowhere to be found within the confines of my Controller module

While working on a personal project, I encountered an issue where a function from another class in a separate Java file is not being found, even though it is defined in the respective class. EventView.js: displayEvent(event){ this.EventTitle = event. ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

Ways to stop Bootstrap collapse from displaying depending on a certain condition in bs5 framework

I've been struggling to figure out how to prevent a collapsible panel from opening or showing if a specific value is null. Despite multiple attempts, I haven't had any success. HTML <a href="#" data-bs-toggle="collapse" da ...

"Using JavaScript to toggle a radio button and display specific form fields according to the selected

Currently, I am attempting to show specific fields based on the selected radio button, and it seems like I am close to the solution. However, despite my efforts, the functionality is not working as expected and no errors are being displayed. I have define ...

Utilizing a function within the App.js file located in the public folder using React JS

I need to execute a function called callMe that is defined in src/App.js from the public folder. In App.js import messaging from './firebase-init'; import './App.css'; function App () { function callMe() { console.log('Call m ...

Tips for enabling autoplay for videos in Owl Carousel

I am facing an issue with implementing autoplay functionality for videos in an owl carousel. Despite trying different solutions found online, including this Owl Carousel VIDEO Autoplay doesn’t work, I haven't been able to make it work. Additionally, ...

Firestore version 9 - Retrieve nested collection depending on a string being present in an array

Working on a new chat application here. It has been a while since I last used Firestore. I am currently using v9 and facing an issue with retrieving the nested "messages" collection when the "users" array in the document contains a specific ID. I have man ...

When working with TypeScript for initial data, you have the choice between using interface types or class types. Which approach is the

When working with initial data in TypeScript, you have the option to use either an interface type or a class type. Which approach is preferable? export interface Item{ text: string, value: number } itemModel: ItemComboBox = { value:'valu ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

Tips for adjusting the color of a <a> tag upon clicking, which remains unchanged until the URL is modified

My goal is to maintain the color of a link when it is clicked. Currently, hovering over the navbar link changes it to greyish, but I want it to remain a different color after clicking on it. I am implementing this using the react-router-dom library for the ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

The Axios GET call encountered an error with a status code of 404

I am currently working on developing a blog/articles application using vue.js. This app utilizes axios to retrieve data from my db.json file by making a get request. The objective is to display the selected article's content when it is clicked on from ...

What is the best way to access nested JSON data in Vue.js code demonstrated here?

How can I properly access the nested JSON data for stage.name provided in the example below? As shown in the template, my attempt to retrieve the stage name is not working. Using vue.js created() { url="http://{{ api_endpoint }}" fetch(url) ...

How can I display options in a react autocomplete feature?

Using the autocomplete component from @material-ui/lab/autocomplete, I am trying to retrieve the title_display result in the options field. These results are being fetched from an API using axios. You can view my code here--> https://codesandbox.io/s/r ...

Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its correspondi ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

When using ng-transclude within ng-repeat, the $transclude function is not available

In my directive, I have a list-like container that transcludes content within an ng-repeat loop. This is the template structure: <div ng-repeat='item in items'> <div ng-transclude></div> </div> Here is an example of ...

Sequencing the loading of resources in AngularJS one after the other by utilizing promises

While working in a service, my goal is to load a resource using $http, store it in a variable, load a child resource and store that as well. I understand the concept of promises for this task, but I am struggling with how to properly implement it in my cod ...

Creating a JSON object using various inputs through AngularJS

Just starting out with Ionic, Angular, and Firebase. This might be a silly question :) I'm working on an app using Ionic + Firebase, and I want to create a JSON object from multiple inputs. The interface looks like the image below: https://i.stack.i ...