Combining two sets of JSON arrays

Looking to combine two arrays based on the same id, merging them into one array.

Example:

 { 
    "id":1212,
    "instructor":"william",
     ...
 }

Array 1:

[ 
     {
        "id":1212,
        "name":"accounting",
         ...
     },
     { 
        "id":1212,
        "name":"finance",
        ...
     }
]

Desired Result:

{        
    "id": 1212,
    "instructor": "william",
    "Courses": [
         { 
            "id":1212,
            "name":"accounting",
             ...
         },
         { 
            "id":1212,
            "name":"finance",
             ...
         }
     ]
}

Answer №1

Your query does not pertain to merging, but here is a method you can use.

const teachers = [{ "id":1212, "instructor":"william", }];
const classes = [ 
  { "id":1212, "name":"accounting" },
  { "id":1212, "name":"finance" }
];

const anticipated = [{ "id":1212, "instructor":"william", "courses": [
  { "id":1212, "name":"accounting" },
  { "id":1212, "name":"finance" }
]}];

const combined = teachers.map(teach => {
  const response = {...teach};
  response.courses = classes.filter(clas => clas.id === teach.id);
  return response;
});

console.log(combined);

Answer №2

Let's create a new array called finArr and an empty array called course.
We will be using a forEach loop in JavaScript to iterate through all the values. Replace varid and varname with your own values.
course.push({"id":varid,"name":varname});
finArr = {"id":variableId,"instructor":variablename,"Courses":course}

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

Vows made in functions, angularjs

I'm trying to figure out how to implement a promise into a function in order to eliminate the use of a timeout. Is this even possible? The function I have is pulling data from a factory called 'Prim' and it looks like this: $scope.getPre = ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

What is the proper technique for looping through an array with an unknown level of nesting?

As I delve into the world of destructuring, there's a specific challenge that has arisen. I'm struggling with how to dynamically display an array of objects depending on their contents... const items={ title: 'Production', subTasks: ...

What is the most efficient way to transfer a string to a python program using ajax and retrieve a string in return?

I'm experiencing a problem with my ajax request where I am sending an object to a python program using JSON: $.ajax({ url: "http://localhost/cgi-bin/python.cgi", type: "POST", data: JSON.stringify(myobject), dataType: ...

Alter the background color of the navigation link in Jquery when the mouse hovers over

I am looking to modify the background color when I hover over various links in my navigation menu. For example, when hovering over link one, the background should turn red; for link two, blue; and for link three, green. However, I also want the backgroun ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

WordPress FlexSlider carousel displays all images on initial slide

I've been using the Nictitate theme for my WordPress website, which comes with a client widget to display logos. I noticed that FlexSlider is used in other widgets within the theme, so I added some code to create a carousel of client logos. Unfortuna ...

Retrieve all elements within a select tag

Currently, I am working with two select-multi lists and I need to retrieve all the elements from the right list, regardless of whether they are selected or not. If you want to see what's happening, feel free to check out my code on jsFiddle The issu ...

Unable to display Material UI table row

I am currently facing an issue while trying to render a table using material UI with fetched data. Despite successfully fetching the data and logging it in its saved state, I encounter a problem when attempting to map this data inside the table row - res ...

.NET 6's JsonSerializer.DeserializeAsync is throwing a null value error when attempting to assign to a non-

I am encountering an issue with JsonSerializer while deserializing a post request from a client. The serialized class has non-null and required properties, but the Json serializer is setting them to null instead of throwing an exception. Current behavior: ...

Move the displayed output in a two-dimensional space

Explore this straightforward example showcasing a cube centered at the world's origin. The camera captures the cube directly, making it appear in the center of the rendered 2D image with only its front face visible. I desire the ability to adjust the ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Delaying the doubling up process

I have a situation with two divs containing start and stop buttons that act as timers. I am creating a JSON object to store time variables and other data. When I click on the start button, the timer functions properly. I assign the timeout function to one ...

What is the best way to convert a JSON into a hashmap with a key and an object value?

Here is the structure of my Json data: { "records": { "fastest": { "30": { "category": "fastest", "timestamp": 1407422694, "value": 2, "group_id": 30, "trip_id": 3429, "id ...

Converting an array of numbers into a single string

I want to transform [1, 2, 3] into ['123']. I need to convert [1, 2, 3] to ['123'] using an arrow function only (no regex): Required steps: const functionOne = (arrayOne) => { }; console.log(functionOne([1, 2, 3])); This is my a ...

Immersive animations with Chart.js

Is there a way for my pie chart to load with its animation as I scroll down the page? Here is the code I am using: <script> var ctx = document.getElementById("myPieChart").getContext("2d"); var myPieChart = new Chart(ctx, { type: 'pie&apos ...

concealing a div within an *ngFor iteration

Attempting to insert a form within a *ngFor loop in order to replicate a button. html file: <div *ngFor="let passenger of passengerForm;let i=index;"> <form> <mat-form-field> <input matInput type="text" placeholder="Ent ...

Vue Router is not updating the router view when the router link clicked is embedded within the view

I have a section called Related Content located at the bottom of my posts page, which displays other related posts. When I click on the Related Content, I expect the router to update the page. However, it seems that although the URL changes, the view does ...

the sequence in which a node executes a javascript function

Trying to update req.session.cart with new values for prod.quantity and prod.qtyCount in the shoppingCart field of order.save(). The issue is that orders are being saved with default quantity and qtyCount values, even though I'm setting cartProducts[ ...

Managing a single repository with multiple packages using npm

Currently, I am in the process of developing a node.js application that requires scalability and maintainability. The concept revolves around having a single repository with multiple modules embedded within it. We have opted to utilize local modules with ...