What is the best way to compare keys and values in a JSON object in Lodash when one object contains additional keys?

Consider the following two JSON objects:

var obj1 = {a: "apple", b: "banana", c: "carrot"}
var obj2 = {a: "apple", e: “egg” b: "banana", c: "carrot", d: "dog"}

I'm looking for a way to compare these objects using a Boolean check without altering any of their data. In this scenario, the comparison should yield true because the values of matching keys in both objects are identical.

Now, let's suppose the first object (obj1) remains the same, but the second one (obj2) is as follows:

var obj1 = {a: "apple", b: "banana", c: "carrot"}
var obj2 = {a: "ant", e: “egg” b: "banana", c: "carrot", d: "dog"}

In this case, the Boolean check should return false because the value associated with key a does not match, even though some other fields do and some are exclusive to one object.

Any suggestions on how to approach this? I'd prefer utilizing Lodash due to its comprehensive feature set. Initially, I tried using _.isEqual(obj1, obj2), but it didn't meet my specific requirements.

Answer №1

Not sure if there is a built-in method in lodash for this specific task, but you can easily achieve the desired outcome using the Object.entries and Array.every methods.

var objA = {
  x: "x-ray",
  y: "yellow",
  z: "zebra"
}
var objB = {
  x: "x-ray",
  y: "yellow",
  z: "zebra",
  w: "whale",
  u: "umbrella"
}


var objC = {x: "x-ray", y: "yellow", z: "zebra"}
var objD = {x: "xylophone", u: "umbrella" ,y: "yellow", z: "zebra", w: "whale"}

function compareObjects(firstObj, secondObj) {
  const entriesFirst = Object.entries(firstObj);
  const entriesSecond = Object.entries(secondObj);

  const shorterArray = entriesFirst.length > entriesSecond ? entriesSecond : entriesFirst; // find the shorter array
  const longerArray = shorterArray === entriesFirst ? secondObj : firstObj;

  const areEqual = shorterArray.every(([key, value]) => longerArray[key] === value);
  return areEqual;

}



console.log(compareObjects(objA, objB))
console.log(compareObjects(objC, objD))

Answer №2

Utilize the <code>_.isMatch function for assistance. Please refer to the code snippet below:

var object1 = {
  name: "John",
  age: 25,
  city: "New York"
}
var object2 = {
  name: "John",
  gender: "Male",
  age: 25,
  city: "New York",
  occupation: "Engineer"
}

console.log(_.isMatch(object2, object1));

var obj1 = {
  color: "blue",
  size: "large",
}
var obj2 = {
  color: "red",
  material: "cotton",
  size: "small",
}

console.log(_.isMatch(obj2, obj1));
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fbf8f3f6e4fff7d3bdc7d8dec7dbd9">[email protected]</a>/lodash.min.js"></script>

Please note that _.isMatch(obj1, obj2) will not provide the desired outcome. An additional logic check is required to determine which object contains more keys and should be passed as the first argument.

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

Having trouble accessing an injector service within the promise of a dynamically loaded JavaScript function that has been assigned to a global variable

Query I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated. ...

Checking for correct HTML tags using JavaScript

Looking to validate some input in javascript and confirm if it is a valid HTML tag. Any straightforward methods with JQuery for this task? If not, any suggestions on how to achieve this using Regex? Thank you! ...

Is there a way to prevent downloaded files from becoming corrupted?

When the handleDownload() function is attached to a button as an event handler (onclick), allowing users to download a file, sometimes the downloaded file ends up corrupted. Is there a way to prevent file corruption? function handleDownload() { ...

Navigating pinch to zoom: Strategies for managing varying page locations

I've been using a combination of JS and CSS to position images within the viewport in a way that allows them to scale and translate accurately to fill the space. For the most part, this method works smoothly and is also able to handle browser zoom fu ...

The arrangement of a JSON array can be modified by AngularJS' Ng-repeat functionality

Hello everyone at SO: On March 18, 2014, I encountered a situation while trying to use ng-repeat. The elements inside the array, retrieved from a Json string, seem to be changing their original order. To clarify, the initial variables in the array pertai ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

What is the best way to implement a prev.next function in an image gallery using an array in JavaScript?

In the image gallery, you can simply click on each image to view a larger version. The enlarged image sources are pulled from the background-image of the smaller images. What I am aiming to achieve is the addition of previous and next buttons for easy navi ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

Utilizing AngularJS for Showcasing JSON Information Using Ng-Repeat and Ng-Factory

As a newcomer to Javascript and Angular, I am currently working on integrating AngularJS into my website. Despite watching tutorials from CodeSchool, Egghead, and others, I seem to be stuck at the very beginning. My issue lies in retrieving JSON data from ...

I created a custom function that combines two arrays into one, but I am encountering an error stating "Unable to access properties of undefined."

I am facing a challenge with combining two arrays into one new array that merges the objects of each array together. While I know how to merge two arrays into a single array, I am struggling to combine the actual objects into a brand new object within that ...

Error message issued by a JSON response indicating an invalid email address while utilizing the PHP GET method within the SendGrid API

Currently, I am utilizing the SendGrid API to send emails. Interestingly, when I attempt to send a single email, everything works perfectly. Moreover, sending emails to multiple email addresses manually also works without any issues. However, the challen ...

Incorporating a GLTF Model in a Basic React Three Fiber Environment

I am attempting to incorporate a model with diffuse and bump textures into a basic scene using react 3 fiber. Despite my best efforts, I can't seem to figure out what mistake I might be making. You can view the sandbox here: https://codesandbox.io/s ...

"Effortlessly handle adding and removing items with a single button using

I am working on creating a button functionality where clicking it will either add or delete a record from the database. This button serves as a 'favorite' feature. The desired behavior is as follows; Upon clicking the 'fav' button, th ...

Iterating through a JSON dataset of various clothing items to search for a specific keyword within the product titles

$(function() { $.getJSON('test.json', function(data) { for (var i = 0; i < data.products.length; i++) { var obj = data.products[i]; if (obj.title.toLowerCase().includes("t-shirt")) { var Imgs = '<div class="Tops">< ...

Data vanished from the input field values

Having an issue with displaying an HTML table inside a .cshtml file. When I hardcode values, the table appears as expected. However, when I attempt to populate it using a foreach loop, the table disappears. <script> var nTable = ""; $(docu ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

TS2688 Error: Type definition file for 'tooltip.js' not found

Why am I getting an 'undefined' error when trying to import the Tooltip class from the npm tooltip.js package in my TypeScript file? ...

What is the proper method for retrieving data using the "current_page" and "timeline" parameters now that the API structure has been updated to only allow objects instead of arrays?

Purpose: Displaying API data in a Tab bar using SwiftUI Approach: I attempted to integrate the API by creating a model and incorporating it into a tab view. However, due to a significant change in the API structure, everything became disorganized. Code s ...