What is the most effective way to compare two complex objects in JavaScript and identify any discrepancies between them?

I have a JavaScript function that takes an object and a pre-existing object. The objective is for the function to add all missing properties from the passed object to the pre-existing one.

While this process is simple when comparing on a single level, it becomes more complex with multiple levels. My goal is something along these lines:

Pre-existing: {hello: "world"}  
Passed: {hello: "there", colour: "green"}
Result: {hello: "world", colour: "green"}

The method involves examining each key of the passed object. If the key does not exist in the pre-existing object, it is added with its corresponding value.

However, extending this functionality to handle multiple levels presents challenges. For example, consider the scenario where:

Pre-existing: {hello: {there: true}}
Passed: {hello: {world: true}}
Result: {hello: {there: true, world: true}}

I envisioned a recursive approach where the function would iterate over the passed object and if it encounters another object, call the function again with that object until all children are processed.

The challenge arises when dynamically comparing the children of both objects across various levels without prior knowledge of the depth or keys involved.

How can one programmatically access the properties of an object at unknown depths while writing code? Hardcoding or using methods like if (result[key1][key2][key3]... may not be feasible, so what alternative approach can be taken?

Answer №1

This response, referenced by @4castle in a related post, may be exactly what you're looking for:

The approach described involves looping through an object and recursively calling the function on any nested objects until all children have been processed.

You've already recognized the need for recursion, which is key in this scenario. JavaScript's for ... in loop enables you to iterate over an object's keys. Just ensure that the target object is indeed an object and not just a value.

The linked answer introduces their own isObject function for this purpose. The recursive object copying is achieved using Object.assign.

Answer №2

To incorporate properties from one object to another, you can utilize a combination of the for..of loop and Object.keys() method. This process involves checking if the property of the passed object is also an object. If it is, then recursively call the function with the original object, the passed object, and the key of the passed object as parameters. Next, assign this property to the original object. If the property is not an object, check if it does not already exist in the original object. If true, assign the passed property to the original object.

var existingObj1 = {
  greeting: {
    message: "Hello"
  }
};

var existingObj2 = {
  name: "Alice"
};

function mergeProperties(properties, obj, key) {
  for (let prop of Object.keys(properties)) {
    if (Object.getPrototypeOf(properties[prop]) === Object.prototype) {
      mergeProperties(properties[prop], obj, prop)
    } else {
      if (key) {
        obj[key][prop] = properties[prop]
      } else {
        if (!(prop in obj)) {
          obj[prop] = properties[prop]
        }
      }
    }
  }
}

mergeProperties({
  greeting: {
    message: "Hi"
  }
}, existingObj1);

console.log("existingObj1:", existingObj1);

mergeProperties({
  description: "World",
  age: 25
}, existingObj2);

console.log("existingObj2:", existingObj2);

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

Introducing the new feature of a React button with the ability to add a

I am looking to enhance my React Button component by adding a new prop called 'type'. This prop will allow the button to either link to another page or execute an onclick event, such as triggering a function when clicked. Below is the current co ...

What is the process for loading an image from the FileSystem using expo?

Can someone help with loading an image from FileSystem in expo? The fileUri is as follows: file:///Users/username/Library/Developer/CoreSimulator/Devices/B9799180-7428-41D8-A4BC-C3A34BF93043/data/Containers/Data/Application/3D502086-E077-42D5-9B56-A1DB788 ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...

Change the DER encoded ANS.1 format of an AWS KMS ECDSA_SHA_256 Signature to JWT base64url encoded R || S format using NodeJS/Javascript

I am currently working on generating a JWT Signature in NodeJS using the ES256 algorithm and AWS KMS Customer Managed Keys. However, I have encountered an issue where the signature created by AWS KMS with ECDSA_SHA_256 cryptographic Signing Algorithms is ...

Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue, I am attempting to create something like this: input key 1 , input value 1 input key 2 , input value 2 < button to add more > < submit button > Essentially, a user can click submit and send a Get req ...

Accessing the req property beyond the route endpoints

const express = require('express'); const router = module.exports = express.Router(); const server = require("http").Server(express); const io = require("socket.io")(server); server.listen(5000); // Need a way to access user.id here router.g ...

Changing CSS classes with each click of the user, using Jquery

Looking for a way to seamlessly switch between two links with different CSS classes each time a user clicks? Here's what's currently happening: <a class="class1" id="class1">Class1</a> <a class="class2" id="class2">Class2</a ...

Unable to find the specified element within Gmail

Recently, I've been working on a project with Nightwatch.js where it checks the dev environment and sends a test email to a Gmail account. Following that, it logs into Gmail, locates and clicks on the correct email. My main challenge now is trying to ...

Transmitting information through socket.emit from the client to the server

I'm facing an issue while trying to send numeric data from the client to the server using socket.emit. The problem is that the server doesn't seem to be receiving any data, as only `null` gets logged or I might be doing something wrong in my appr ...

Error: Unable to find module 'app' in the injector. This issue is specific to Firefox browser

I've hit a roadblock with this issue. Despite reading extensively about it, I can't seem to solve it. The problem arises when I declare my <script> app.js before utilizing ng-app, leading to the following error: Failed to instantiate modul ...

What could be causing the issue when attempting to execute the "npm start" command on a Mac?

I've been encountering issues while trying to install npm. Initially, I faced an error due to the absence of a package-lock.json file and package.json file, which was resolved by running "npm init" in the terminal. Subsequently, when attempting to ex ...

Transforming JSON data into an object model

Looking to parse some JSON data: { "apple" : [ { "type" : "red" }, { "type" : "green" } ] } I'm trying to convert this into a collection using the following custom class: public class Fruit { public string type { get; s ...

I'm experiencing difficulty displaying my nested array in JavaScript

let array2 = ['Banana', ['Apples', ['Oranges'], 'Blueberries']]; document.write(array2[0][0]); In attempting to access the value Apples within this nested array, I encountered unexpected behavior. Initially, access ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

Compressing an array of key-value pairs into a concise JSON string

I am considering different ways to store an array of key value items in JSON data. One common method is shown below: // the JSON data may store several data types, not just key value lists, // but, must be able to identify some data as a key value list / ...

Javascript: Troubleshooting Unexpected Variable Behavior in HTML Code

My issue is as follows: I am attempting to retrieve text from a JSON file in my HTML. In the header of my HTML, I have linked a tag with the following code: var language = ""; var langDoc = null; //Function to change the value function setLang() { v ...

Passing props to child components in Next.js: A step-by-step guide

I am currently working with my index.js page, which incorporates a layout component: import Layout from "../components/layout"; export default function Home({posts}) { console.log(posts) return ( <Layout posts={posts}> & ...

iOS hover menu behavior: Close dropdown when the same element is tapped again on iPads

The navigation bar features categories such as: politics, economy, education Upon clicking on these categories, a dropdown menu appears with locations like: asia, europe, North America What I am looking for is this: If the user clicks (tabs) or hovers (o ...

Displaying a PHP array in JSON format using jQuery

I've been trying to display an array using jQuery, but I just can't seem to get it right :P After spending the last hour on Google and here, I still can't figure out what I'm doing wrong.. This is my array: if (isset($_POST['ima ...