Updating a specific property within an array of objects by identifying its unique id and storing it in a separate array of objects

Struggling to merge these two arrays? Look no further! By comparing the parent id to child parentsId, you can effortlessly push the second array as an extra property to its parent. Save yourself hours of frustration and achieve your desired output with a little help.

Array 1

const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
      },
    ];

Array 2

const child = [
      {
        parentId: 1,
        name: 'mike',
        age: 5,
      },
      {
        parentId: 2,
        name: 'michelle',
        age: 6,
      },
      {
        parentId: 2,
        name: 'morgan',
        age: 7,
      },
    ];

Desired result: Populate the child elements into their respective parent objects based on parentId.

  const parent = [
      {
        id: 1,
        name: 'john',
        age: 32,
        children: [
          {
            parentId: 1,
            name: 'mike',
            age: 5,
          },
        ],
      },
      {
        id: 2,
        name: 'jane',
        age: 44,
        children: [
          {
            parentId: 2,
            name: 'michelle',
            age: 6,
          },
          {
            parentId: 2,
            name: 'morgan',
            age: 7,
          },
        ],
      },

Answer №1

If you want to merge arrays in JavaScript, you can utilize a combination of .map(), .filter(), and spread syntax:

const parent = [{ id: 1, name: "john", age: 32 }, { id: 2, name: "jane", age: 44}];
const child = [{ parentId: 1, name: "mike", age: 5}, { parentId: 2, name: "michelle", age:6}, { parentId: 2, name: "morgan", age: 7}];

const result = parent.map(person => ({
  ...person,
  children: child.filter(({ parentId }) => parentId === person.id)
}));

console.log(result);

JUST A QUICK NOTE: It's uncertain why your question got closed down. It might not be due to lack of focus. Maybe it was because you didn't explain how you attempted to tackle the issue or the errors you encountered. Remember to include more details next time for better assistance.

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

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

The jQuery window.on event is not functioning when trying to handle the same hash change

How to fix jQuery window.on hashchange issue when clicking on the same hash? See the code snippet below for a potential solution: function addMargin() { let header = $('.header__wrapper').outerHeight(); let headerHeight = $('body& ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Divide HTML elements every two words

Can you use CSS to break up HTML content after every 2 words, ensuring it works for any word combination? Example: // Original HTML content The cat is sleeping // Desired result: The cat is sleeping ...

Searching for a specific element within a JSON object by iterating through it with JavaScript

Here is the JSON file I am working with: { "src": "Dvc", "rte": { "src": "dvc" }, "msgTyp": "dvc.act", "srcTyp": "dvc.act", "cntxt": "", "obj": { "clbcks": [ { "type": "", "title": "", "fields": [ { "src": "label.PNG", ...

Contrast between $foo[bar] versus $foo['bar'] in PHP

For a while, I've been utilizing $foo[bar] in various projects without realizing the absence of '. Recently, I have come to understand why it still functions. My assumption is that a missing constant gets substituted by its name, which ultimatel ...

Function with pointers in C cannot be executed

Greetings everyone, I'm a newbie on stack overflow! :D I encountered this error: An unhandled exception occurred at address 0x0105F338 (ucrtbased.dll) in Assignment_5.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD. Exception thrown ...

Deleting all JSON files in a directory using NodeJs

Is there a way to delete only the json files within a directory (multiple levels) without specifying each file name individually? I thought fs-unlinkSync(path) might work, but I haven't found that solution yet. I attempted to use the following method ...

The Material UI component successfully loads the options data list from the server response, however, it fails to return the selected value when an option

My goal is to dynamically populate my country and province select component based on server response data. The process begins with the user selecting a country, which triggers a request to the server using the selected country's id. The server respond ...

IDEA 2021.2 NPM SCRIPTS: Looks like there are no scripts available

Searching through the npm scripts, I am unable to locate any, however package.json does contain: ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...

Tips for utilizing the multiselect() function without deleting current values and incorporating new values determined by another selection

Currently, I am working on an e-learning project that involves managing a large number of student registrations. I have implemented a search box to find students' names and add them to a list. However, I encountered an issue when trying to search for ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

Dynamic Line Animation with React Three Fiber

Is it possible to create a similar effect like the one showcased on this website: I'm looking to incorporate a dashed moving line that indicates direction. I prefer to use r3f, but regular three.js would also work. The background design is also app ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

How to Invoke JavaScript Functions within jQuery Functions?

I'm working on a jQuery function that involves dynamically loading images and checking their width. I have two JavaScript functions, func1() and func2(), that I want to call from within the jQuery function in order to check the width of each image. T ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...