Ways to evaluate and contrast two JSON values in JavaScript by their key names?

I am dealing with two JSON arrays that look like this:

array1=[{a:1,b:2,c:3,d:4}]
&
array2=[{a:2,b:5,c:3,d:4}]

Is there a way to determine which key in array2 has the same value as one of the keys in array1? For example, in array 1, key b has a value of 2, and in array2, key a has a value of 2. How can I identify the key name in array2 that matches the value of a key in array1?

Answer №1

It seems like there may be some confusion about whether you are looking to work with arrays or objects based on your example of single element arrays and the comparison being made between the objects within them.

If your intention is to compare two objects and find the keys that are the same in both, a simple function like the one below could achieve that:

let firstObject = {apple: 1, orange: 2, banana: 3};
let secondObject = {apple: 2, orange: 5, banana: 3};

function findMatchingKeys(x, y) {
    return Object.keys(x).filter(function(key) {
        return x[key] === y[key];
    });
}

console.log(findMatchingKeys(firstObject, secondObject));

Upon running this code, the output should be:

[ 'banana' ]

I hope this clears up any confusion you had regarding the comparison of objects in JavaScript.

Answer №2

Developed a prototype method to compare properties of one object with another.

let object1 = {apple: 1, banana: 2, cherry: 3, date: 4};
let object2 = {apple: 2, banana: 4, cherry: 100, date: 200}

Object.prototype.compareProperties = function(otherObject) {

   let result = {};

   for (key in this) {
        if (!this.hasOwnProperty(key))
          continue;

        for (otherKey in otherObject) {
           if (otherObject[otherKey] === this[key])
              result[otherKey] = key;               
      }   
   } 

  return result;

}

console.log(object1.compareProperties(object2));

To use the compareProperties method on any object, simply provide another object as an argument. It will return related keys between the two objects.

The output from the example above would be:

{apple: "banana", banana: "date"}

Answer №3

If you're looking for a solution, here's a suggestion: create a function that can identify all the keys in the second object which have a specific value. Then, you can input the value from the first object into this function.

firstObj={x:10,y:20,z:30};
secondObj={x:15,y:25,z:35};
function getKeysByValue(obj, val) {
    var output = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key) && val == obj[key]) {
            output.push(key);
        }
    }
    return output;
}
console.log(getKeysByValue(secondObj, firstObj['y']));   // ['y']

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

Assigning objects in Vue.js methods

I am working on a Vue component where I need to select a specific value from an array of objects and then copy certain fields from that value into Vue data. <div class="container"> <h4>Add Item</h4> <form @submit.prevent="ad ...

The result of Coordinates.speed is consistently null

I'm working on a project that involves changing the speed of background particles based on the user's device speed (like when they are in a car or bus). I thought the Geolocation API would be a perfect fit, specifically the Coordinates.speed prop ...

Struggling to understand the process of creating a new page in Express

I've created a file called ships.js in my routes folder: var express = require('express'); var router = express.Router(); /* GET Ships page. */ router.get('/ships', function(req, res, next) { res.render('ships', { tit ...

How to Send Data to ASP.NET MVC Controller Using AJAX Request with jQuery

I am trying to send parameters to a controller from jQuery, but I am struggling with it. The call works fine without parameters when the URL is just /SurveySection/EditLocalization. Shouldn't it be something like this: /SurveySection/EditLocalization? ...

Searching for the location of the apoc.conf within the Neo4j sandbox?

Just started using neo4j for the first time and I'm running it on my browser since my desktop version is not working. I'm trying to load JSON into it, but I keep getting an error message that says: Failed to invoke procedure `apoc.load.json`: Ca ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...

looking to implement auto-scroll feature in flatlist using react native

I'm attempting to implement auto-scroll functionality in my FlatList, but I'm encountering a problem where the list does not scroll automatically. Additionally, whenever I try to manually scroll, it reverts back to index 0 every 5 seconds. Below ...

How can I extract information from an iCal file to display the upcoming event?

Is there a method to extract information from an iCalendar file and display the most recent event using JavaScript or node.js? Your assistance on this matter would be greatly valued. Many thanks ...

Easier method for creating json body for reqwest post requests

I've implemented a post call that adds one line in register, and while it is functional, the code is cumbersome to write and read. Here's how it currently appears: static CLIENT: Lazy<Client> = Lazy::new(|| Client::new()); static GENER ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

Breaking auto-update functionality when using the 'dd-slick' jQuery plugin to style chained drop-downs

Utilizing the jquery.ddslick.min.js plugin from jQuery for creating customized drop-down menus with image options. Additionally, incorporating the jquery.chained.min.js script to automatically update the content in the second select box based on the select ...

Attempting to retrieve JSON data from an API while currently working from local server

I need to retrieve JSON data from , but I keep encountering the error message: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access." Here is the code I ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

What is the best way to execute the angular-phonecat tutorial tests while the server is operating without a graphical user interface?

The angular-phonecat demo assumes that your server has chrome installed and you are running it there. When you run the command npm test, the local chrome browser should launch and continuously run the tests. However, if you are using a headless server li ...

Failed to access JSON information from the Fitbit OAuth2 API

I am currently utilizing the fitbit api with PHP, attempting to simply echo the json data, but I am encountering an issue with receiving an invalid request error in the JSON data. The workflow I am following is as follows: First, I visit , where the code b ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

Retrieve libraries from package-lock.json file

I am tasked with extracting all the libraries and versions from the package-lock.json file. Let me provide some context. I am implementing a security module within Jenkins to create an inventory of libraries used in each application. The goal is to gather ...

List of images using React Native's FlatList

Seeking assistance with integrating images into a flatlist grid. I have successfully implemented text but struggling with images stored in the assets folder. The goal is to display separate images from the assets folder within the boxes of the flatlist gr ...