Comparing arrays with objects containing different sequences in JavaScript: A guide

I have two arrays where I need to identify matching values across different sequences. How can I achieve this comparison using plain JavaScript? Specifically, I am trying to match the values of property1 and name and then extract property3 when property1 matches name.

Here is the code snippet:


var data = [];
var data1 = [
    {'property1': 'john', 'property2': 12}, 
    {'property1': 'jasmin', 'property2': 22}, 
    {'property1': 'dog', 'property2': 22}
];
var data2 = [
    {'name': 'dog', 'property2': 12, 'property3': 'xys'}, 
    {'name': 'john', 'property2': 22, 'property3': 'acb'}, 
    {'name': 'jasmin', 'property2': 22, 'property3': 'jjj'}
];

for(var i=0; i<data1.length; i++){
    if(data1[i].property1 == data2[i].name){
        data.push({
            'property1': data1[i].property1,
            'property2': data1[i].property2,
            'property3': data2[i].property3
        }); 
    } else {
        console.log('not equal');
    }
}

The jsfiddle link for reference

The expected output should be:


data=[{'property1': 'john', 'property2': 12, 'property3': 'acb'},
{'property1': 'jasmin', 'property2': 22, 'property3': 'jjj'}, 
{'property1': 'dog', 'property2': 22, 'property3': 'xys'}]

Answer №1

var information = []
var information1 = [
    {'property1': 'john', 'property2': 12}, 
    {'property1': 'jasmin', 'property2': 22}, 
    {'property1': 'dog', 'property2': 22}
];
var information2 = [
    {'name': 'dog', 'property2': 12, 'property3': 'xys'}, 
    {'name': 'john', 'property2': 22, 'property3': 'acb'}, 
    {'name': 'jasmin', 'property2': 22, 'property3': 'jjj'}
];

information = information1.slice().map(function(element){
    for (var index = 0, length = information2.length; index < length; index++) {
        if (element.property1 === information2[index].name) {
            element.property3 = information2[index].property3;
        }
    }
    return element;
});

console.log(information);

information1.slice().map(...) operates on a duplicate of the initial array, ensuring we do not modify the original data within the loop.

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

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Toggle visibility

Seeking a unique example of a div SHOW / HIDE functionality where multiple divs are populated within the main container. Specifically looking to display new paragraphs or topics of text. I have experience with standard show/hide techniques for collapsing ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

Plugin for Cordova that enables detection of internet connectivity

I'm currently working on my Cordova app which requires an internet connection for certain actions. To monitor the network status, I am utilizing a plugin called https://github.com/apache/cordova-plugin-network-information. The plugin successfully dete ...

What is the fastest method for populating a 2-dimensional std::array and std::vector efficiently?

When working with multidimensional arrays and vectors, I usually rely on the .fill() method for 1D arrays. However, it seems that this method does not work with arrays of higher dimensions. I have come across various methods to fill them, but I am curious ...

Marionette stores a collection for various item views

I am currently working on a project involving a composite view called QueueItems, with each item in the collection having its own itemView for modification. The challenge lies in allowing each element to select from multiple tag collections like States, Co ...

When a mobile device is rotated, the screen on a jQuery application will automatically shrink

Having trouble with JQM and device rotation on iOS devices. The screen doesn't resize properly when rotated. I have this line in the header to handle display size: <meta name="viewport" content="height=device-height,width=device-width,initial-scal ...

Personalize Bootstrap 5 slider for mobile (displaying multiple items without being arranged in a single row)

Having trouble customizing the carousel layout for mobile devices. I'm trying to display all items of the carousel on mobile instead of just one. I've been experimenting with CSS and JS, specifically with the display, float, or max-width properti ...

What is the best way to handle query string parameters when routing in Next.js?

One of the challenges I am facing is related to a URL structure like this: bar?id=foo When I navigate to this URL using router.push('bar?id=foo'), everything works perfectly. However, if I directly access the route in the browser, the query st ...

What is the best way to include the application version in an Electron project using JavaScript

While attempting to publish an update for my app, I encountered a strange error. Can anyone pinpoint the issue? (Note: Node.js is included) Error Message: Unexpected token < <script> console.log(process); let output = <h2 class="page- ...

Cluster multiple markers on a Google Map using Angular

It's surprising that there are no examples discussing the utilization of multiple MarkerClusterers in AngularJS Google Maps. To showcase my code, I have created a Plunker: http://plnkr.co/edit/TlkZ18IMbWKxI8pdgwko?p=preview The structure of the tem ...

Transforming a JSON object into a list in C#

After exploring similar posts without success, I am reaching out here for help. I have a Json data stored in a hidden field that I am trying to access in the code behind file of my markup page. My goal is to convert this Json into a List and bind it to a ...

Creating a textured 3D model utilizing three.js with <canvas> instead of WebGL

While Three.js is typically used with WebGL, I am intrigued by the idea of using its CanvasRenderer due to compatibility concerns. My main requirement, however, is the ability to work with textured models. I came across this unique demo that demonstrates ...

Using AngularJS in combination with a Flask backend to visualize the data being sent from the backend

I am currently developing a Single Page Application using Angular with a Python/Flask backend that connects to MongoDB. The challenge I'm facing is that, although I can retrieve data from the backend using a $http get request in Angular as an object ...

Modify the buttons in the Angular Material Nav-bar according to the current page

I've utilized Angular Material to design my navbar in the app.component.html page. Initially, it features a LOGIN button which should be hidden once the user successfully logs in. Current method: I'm currently disabling the login button based on ...

How to dismiss a jQueryMobile dialog without triggering a page refresh

I've encountered a question similar to this before, but there wasn't any solution provided. The issue I'm facing is that I have a form and when a user clicks on a checkbox, I want to open a popup/dialog for them to enter some data. However, ...

Doubt surrounding the behavior of Node.js when a file is required that does not export anything from a module

My understanding of Node.js' require() function and module.exports is high-level, but I still find some behaviors confusing. Imagine I have two simple one-line files named a.js and b.js. In a.js: require('./b.js'); and in b.js: console. ...

When employing Flatlist, an issue arises where the image fails to appear on the screen, accompanied by an error message stating "value for uri cannot be cast from Double to String."

I'm facing an issue with displaying images in my flatlist. The error message I receive is "Error while updating property 'src' of a view managed by : RTCImageView." Can anyone help me identify what might be causing this problem in my code? ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...