Tips for updating the First object based on certain matching values from the Second object using JavaScript

I am faced with the task of updating the listOfStudents Object by matching it with the homeworkResults Object based on their corresponding email values. Through comparison, when the email matches between the two Objects, I aim to retrieve the topic and success values and update the listOfStudents Object. This task must be achieved solely using Javascript.

The expected outcome should resemble the following:

name: 'John',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb0979d91999cde939f9d">[email protected]</a>',
results: [
        {
            topic: 'HTML Basics',
            success: true
        },
        {
            topic: 'CSS Basics',
            success: false
        }
] 
const listOfStudents = [
    {
        name: 'John',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0dadfd8def0d7ddd1d9dc9ed3dfdd">[email protected]</a>'
    },
    {
        name: 'Jane',
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a3a8a7ac89aea4a8a0a5e7aaa6a4">[email protected]</a>'
    }
];

const homeworkResults = [
    {
        topic: 'HTML Basics',
        results: [
            {
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e444146406e49434f4742004d4143">[email protected]</a>',
                success: true
            },
            {
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e646f606b4e69636f6762206d6163">[email protected]</a>',
                success: true
            }
        ]
    },
    {
        topic: 'CSS Basics',
        results: [
            {
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e9ecebedc3e4eee2eaefade0ecee">[email protected]</a>',
                success: false
            },
            {
                email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b212a252e0b2c262a222765282426">[email protected]</a>',
                success: true
            }
        ]
    }
];

Answer №1

Utilize the map function on the listOfStudents array. When constructing the results array, employ the reduce function on the homeworkResults array. Within the callback function, utilize the find method to locate the object with a matching email address. Then extract the success and topics.

const listOfStudents = [{
    name: 'John',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="177d787f7957707a767e7b3974787a">[email protected]</a>'
  },
  {
    name: 'Jane',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3359525d5673545e525a5f1d505c5e">[email protected]</a>'
  }
];

const homeworkResults = [{
    topic: 'HTML Basics',
    results: [{
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2a8adaaac82a5afa3abae0a8a5adb4a9a9a2ada2eaa7aba9">[email protected]</a>',
        success: true
      },
      {
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd5ded1daffd8d2ded6d391dcd0d2">[email protected]</a>',
        success: true
      }
    ]
  },
  {
    topic: 'CSS Basics',
    results: [{
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e882878086a88f85898184c68b8785">[email protected]</a>',
        success: false
      },
      {
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f454e414a6f48424e4643014c4042">[email protected]</a>',
        success: true
      }
    ]
  }
];
// The map function will return an array
let data = listOfStudents.map((student, index) => {
  return {
    name: student.name,
    email: student.email,
    // Inside the reduce callback, use find to retrieve the object where 
    // the email matches. If a match is found, extract the topic and success
    results: homeworkResults.reduce((accumulator, current) => {
      const resultByEmail = current.results.find(element => element.email === student.email);
      accumulator.push({
        topics: current.topic,
        success: resultByEmail.success
      })

      return accumulator;
    }, [])

  }
});

console.log(data)

Answer №2

Using a loop to iterate through a list of students and filter out specific homework results for each student based on their email address. Then performing an operation to modify the elements of the list.

Answer №3

My process involves mapping through listOfStudent and within that, mapping through homeworkResult to extract filtered and modified data.

var listOfStudents = [ { name: 'John', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7812171016381f15191114561b1715">[email protected]</a>' }, { name: 'Jane', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e48e858a81a48389858d88ca878b89">[email protected]</a>' }];

var homeworkResults = [ { topic: 'HTML Basics', results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="355f5a5d5b755258545c591b565a58">[email protected]</a>', success: true }, { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e9e2ede6c3e4eee2eaefade0ecee">[email protected]</a>', success: true } ] }, { topic: 'CSS Basics', results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b616463654b6c666a626725686466">[email protected]</a>', success: false }, { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395358575c795e54585055175a5654">[email protected]</a>', success: true } ] }];

var result = listOfStudents.map(val=>{
    result = homeworkResults.map(({topic, results})=>({topic,...results.filter(v=>v.email==val.email).map(d=>({success:d.success}))[0]}));
    return {...val, result}
});

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 characteristics and functions of the THREE.TransformControls

I've been attempting to utilize transformControl in my program, but due to the lack of documentation on controls at threejs.org, I find it challenging to tap into its full potential. I'm seeking information on all the properties and methods provi ...

The process of extracting text from an HTML element using Selenium and Node.js

After searching extensively on stackoverflow, I came up empty-handed in finding a solution to my problem. Can anyone lend a hand? I am trying to extract the text from an HTML element using the following code: var element = driver.findElement(webdriver.By ...

Is it possible to verify the user's authentication by confirming the presence of a JWT in their localStorage?

I am currently working on a project that requires JWT authentication. I have set up a registration form and login page where users receive an authorityToken and it is saved in localStorage. Once the user logs into their account : ` $("#btnLogin").click( ...

What steps should I take to address the issue of fixing the classname rather than using the

<div ng-class:"{{myclass}}" role="progressbar" aria-valuenow="{{roundedtotalPerformanceCount}}" aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( totalPerformanceCount + '%' ) }"> {{roundedtotalPerformanceCou ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

Purging the internal buffer of the node stream

Utilizing Node Serialport, I've implemented an event listener to check the data streaming through the connection for correct units. If the units don't match what the user has set, I utilize the .pause() method to pause the stream and inform the u ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

Creating a production-ready webpack bundle with minimized dependencies

Suppose there exists a module on npm known as "awesomepackage". I am able to declare it as a dependency for my application using package.json by executing: npm i --save awesomepackage Upon examining my node_modules directory, I come across a folder label ...

An error notification received from the command "jspm install jquery"

As I follow the tutorial on the jspm.io site, everything goes smoothly until I reach step 3. When I try to execute jspm install jquery, an error message pops up. The error reads: warn Error on getOverride for jspm:github, retrying (2). ReferenceError: ui ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...

A stylish method for converting CSV data into XML format using Node.js and Express

I am in search of a sophisticated solution to convert CSV files into hierarchical XML format based on a specific template within a Node/Express server. For example, if the CSV is of Type Template "Location": Name,Lat,Lon,Timezone name,lat,lon,timezone it ...

What is the mechanism by which Redux sends state to mapStateToProps?

I'm currently delving into the inner workings of React and Redux, and recently came across FuelSavingsPage.js in this sample project. While I grasp how actions is obtained in mapDispatchToProps, I am uncertain about how state is passed to mapStateToPr ...

Displaying variables as HTML in Node.js involves rendering the variable data

Currently experimenting with displaying a Node.js variable as HTML. This is my setup in app.js using Express: Package.json "dependencies": { "body-parser": "~1.12.0", "cookie-parser": "~1.3.4", "debug": "~2.1.1", "express": "~4.12.2", ...

Struggling with sending data to a modal in AngularJS?

I am dealing with the following code snippet $scope.currentTask = undefined; $scope.openModal = function (task, size, parentSelector) { var parentElem = parentSelector ? angular.element($document[0].querySelector('.modal-d ...

Error message: When the mouse hovers over, display the chart(.js) results in TypeError: t is

I encountered a persistent error that I just can't seem to resolve. My goal is to showcase a chart using Chart.js when the mouse hovers over the canvas. However, upon hovering over the canvas, I keep getting a TypeError: t is null error. Error: { ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

The click function operates only once

Here are two simple JavaScript functions: CTCC.Transactions.PieceRecuClick = function (source) { $(".chk input[type='checkbox']").attr('checked', true); } CTCC.Transactions.PieceNonRecuClick = function (source) { $(".chk input ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...