Comparing two arrays of objects in JavaScript using key and value pairs

I have two different arrays of objects listed below. I aim to compare them and determine the score based on matching random codes. The sample result is outlined for reference. Thank you.

me.records.data1(array of objects)

[
        {
            id: 345,
            user: 223,
            random_code: "50-3910111611011",
            created_at: "2019-03-01",
            is_verified: false,
            …
        }   1:{
        id: 346,
            user:223,
                random_code:"50-101966854102",
                    created_at:"2019-03-01",
                        is_verified:false,
      …
   }
]

me.records.data2(array of objects)

[  
   {  
      id:161,
      questionaire_content:80,
      questionaire_content_choice:272,
      created_at:"2019-03-01",
      random_code:"50-3910111611011",
      score:"0",
      …
   }   1:{  
      id:162,
      questionaire_content:79,
      questionaire_content_choice:270,
      created_at:"2019-03-01",
      random_code:"50-101966854102",
      score:"1",
      …
   }
]

The resulting data, based on the provided information:

]{  
id:345,
user:223,
random_code:"50-3910111611011",
created_at:"2019-03-01",
score:0,
is_verified:false,
…
}{  
id:346,
user:223,
random_code:"50-101966854102",
created_at:"2019-03-01",
score:1,
is_verified:false,
…
}

]

Answer №1

To achieve the desired outcome, follow these steps:

  1. Go through each element in the source array.
  2. For every item in the source array, extract the value associated with the "random_code" key for the object and save it in a temporary variable.
  3. In the scores array, locate an object that has a matching "random_code" to the one stored in the temporary variable; if found, retrieve the value associated with the "score" key.

const source = [
  {
    id: 345,
    user: 223,
    random_code: "50-3910111611011",
    created_at: "2019-03-01",
    is_verified: false,
  }, {
    id: 346,
    user:223,
    random_code:"50-101966854102",
    created_at:"2019-03-01",
    is_verified:false,
  }
];

const scores = [
  {  
      id:161,
      questionaire_content:80,
      questionaire_content_choice:272,
      created_at:"2019-03-01",
      random_code:"50-3910111611011",
      score:"0",
   }, {  
      id:162,
      questionaire_content:79,
      questionaire_content_choice:270,
      created_at:"2019-03-01",
      random_code:"50-101966854102",
      score:"1",
   }
];

// Function to fetch the score value from the scores array based on matching random code.
const getScoreForRandomCode = (randomCode) => {
  for (let index = 0; index < scores.length; index++) {
    const tempScore = scores[index];
    if (tempScore.random_code === randomCode) {
      return tempScore.score;
    }
  }
}

const result = source.map ((item) => {
  const randomCode = item.random_code;
  const score = getScoreForRandomCode (randomCode);
  return {
    ...item,
    score: score || 'NA'
  };
});

console.log (result);

Answer №2

Iterate through each element in me.records.data1 using the forEach method, and compare the random_code with those in me.records.data2. If there is a match, assign the score from data2 to the corresponding element in data1.

me.records.data1.forEach(function(obj){  
    var bscore = ""; 
    data2 = me.records.data2.find(function(i) { if(i.random_code === obj.random_code) return i.score; });
    if(bscore!="") obj.score = data2.score;
});

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 comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Invoke JavaScript function upon page load

There is a link on my page that, when clicked, opens a login popup. However, I am struggling to make it work on page load. I have spent a lot of time trying to figure this out, but nothing seems to be working. <a id="onestepcheckout-login-link" href=" ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Utilizing an array as an index for a vector in MATLAB

While browsing through some matlab code, I noticed an interesting use of indexing involving a 1D vector named "signal" with a length of 100 being indexed by a 3D matrix named "distances" with dimensions 10x10x10. The result of this operation, "signal(dista ...

Integrate Javascript code into a JavaScript file

Is there a way to incorporate a JavaScript link inside a .js file? Does a .js file support include, require, or import similar to CSS or PHP? Here is the code in question: // Global site tag (gtag.js) - Google Analytics var script = document.createElemen ...

Instructions for using arrow keys to navigate between div elementsHow to use arrow keys for navigating through

Is it possible to navigate between div elements using arrow keys like in Notion's editor? <div> hello word </div> <div>hi</div> <div>notion</div> Given the code above, how can one move the cursor to another ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

WebClient executes JavaScript code

On my aspx page, there are JavaScript functions that handle paging. I am currently using the WebBrowser control to run these JavaScript functions by calling WebBrowser1_DocumentCompleted. WebBrowser1.Document.Window.DomWindow.execscript ("somefunction(); ...

Removing an element from an array in PHP results in adding a key to objects

When extracting data from a json feed, I specifically require four objects located at $json['content']['locations']['location']['cams']['cam']['snow']['wi']. Despite there being 5 objec ...

Adding style using CSS to a dynamically generated table row in Vue.js

Currently, I am working with a table that dynamically generates rows using v-for: <table> <tr><th class='name'>Name</th><th>Surname</th></tr> <tr v-for='data in datas'><td class=&a ...

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

Attempting to remove certain characters from a given string

let currentDate = new Date(); currentDate.toLocaleString; If I were to console log the value of currentDate, it would show: Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time) However, what if I only want to display the minutes and seconds like 57: ...

Tips for restoring lost data from localStorage after leaving the browser where only one data remains

After deleting all bookmark data from localStorage and closing my website tab or Chrome, I am puzzled as to why there is still one remaining data entry when I revisit the site, which happens to be the most recently deleted data. This is the code snippet I ...

Problem with geocoding to retrieve a list of terrestrial coordinates

I am currently working on developing a functionality that can return an array of land-based coordinates. I have utilized Google's geocoder to create individual land-based coordinates successfully, but now I want to implement it in a way where an array ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

Issue: spawn command UNKNOWN while running npx create-react-app

Encountering an error message in the command prompt while trying to create a React app. Here are some details: Node version: v16.16.0 Npm version: 8.15.1 Operating system: Windows 11 Attempted solutions include running the command in PowerShell, cleari ...

Forecasting the Asynchronous Behavior of Promises

I encountered a piece of code that left me puzzled about the flow of execution. var x = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve([1, 2, 3]); }, 0); }); }; x().then((val) => { console.log ...

Creating session variables in Joomla using checkboxes and AJAX

I'm currently working on implementing session variables in Joomla with AJAX when checkboxes are selected. Below is the code snippet from select_thumb.ajax.php file: $_SESSION['ss'] = $value; $response = $_SESSION['ss']; echo ...

toggle the class on a label that contains a checkbox

Is there a way to use toggleClass to add a class to a label when clicked, even if the label contains a checkbox? Currently, I am having an issue where the class is only added when clicking directly on the checkbox. How can I make it so that the class is ad ...