Exploring the Distinctions among JavaScript Objects

Currently facing a challenging problem and in search of an efficient solution.

I have two Javascript Objects structured as {id:data, id:data, ..}

If we focus solely on the Keys, they appear like this:

B = ["1","2","3"]
A =     ["2","3","4"]

My goal is to figure out how to transform B into A. For instance, Delete B.1 and B.4 so that it matches A.4 .

I've been contemplating whether creating a prototypal function for Object would be a viable approach.

This is my current implementation:

Array.prototype.diff = function(a) {
          return this.filter(function(i) {return a.indexOf(i) < 0;});
      };
Object.prototype.syncTo = function(b,callbackA,callbackB){
                var a = this;
                var bKeys = Object.keys(b);
                var aKeys = Object.keys(a);

                var toremove = bKeys.diff(aKeys);
                var toadd = aKeys.diff(bKeys);

                for(var i = 0; i < toremove.length; i++) {
                      if(b.hasOwnProperty(toremove[i])) {
                          delete b[toremove[i]]; 
                      }
                }
                callbackB(b);
                for(var i = 0; i < toadd.length; i++) {

                      if(a.hasOwnProperty(toadd[i])){
                      <<Struggling with next steps>>    
                      }
                }
                callbackA(XXXXXX);
};

The idea behind CallbackA is to add elements to B, while CallbackB involves removing elements from B based on the transformation needed.

Currently grappling with determining the elements for callbackA and evaluating the efficiency of this process.

Appreciate your guidance and assistance!

EDIT: An example callback could be :

callbackB:

    function (items){ 
      for(var i in items){
         items[i].removeSomeWhereElse(); 
      } 
    }

Answer №1

If you're searching on NPM, you'll find a few libraries that can handle this task. Allow me to shamelessly suggest one that I created myself, capable of diffing any object with array insertion/deletion/moves:

Check out https://github.com/benjamine/jsondiffpatch

For a demonstration of comparing 2 arrays, visit the following link:

You can easily spot deletes, additions, and even moves (move detection can be disabled via configuration if needed).

Opting for this library will save you time efficiently. However, if conserving CPU cycles is your priority, consider implementing a simple version of LCS (the standard algorithm for solving the described problem). Check out more about LCS here: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

jsondiffpatch already includes an implementation for js, which you can use directly from this link: https://github.com/benjamine/jsondiffpatch/blob/master/src/filters/lcs.js

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

The button with type Submit inside the form is failing to trigger the Form Submit Event

Having an issue with a custom LoadingButton component in my React TypeScript project using Material-UI (MUI) library. The problem occurs when using this LoadingButton within a form with an onSubmit event handler. The LoadingButton has type="submit&quo ...

Set up linter rules that utilize `useEffect` in place of `React.useEffect` (utilizing named export rather than full export)

It's important in our codebase to always use: import { useEffect } from 'react'; instead of: import React from 'react'; // use in code as `React.useEffect` Can we enforce this rule with longer eslint rules? If so, how can we impl ...

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...

The functionality of wp_script_is in WordPress seems to be malfunctioning when it comes to

I need to load a certain file only after a specific script has finished loading. Wordpress offers a useful method called 'wp_script_is' for detecting if a script has loaded or not. When I use the jquery handle with "done", it functions as expecte ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Issue with Canvas.doDataUrl not functioning properly in presence of an image on canvas

It seems like the code I have tried only works for local images. Can someone share a working code snippet for this? Here is what I've attempted: var base_image = new Image(); base_image.src = ("/img.png"); base_image.onload = function(){ var co ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

Error: The 'inputValue' property in the Select component of antd is malfunctioning

Currently, I am utilizing the antd library's Select component (version v3.23.1) with the mode="multiple" setting. I have observed that when I type in the search field within the Select component and then click outside of it, the searched text gets cle ...

What is the most efficient method for choosing a class with jQuery?

I'm dealing with a Bootstrap button: customtags/q_extras.py @register.filter(name='topic_check') def is_topic_followed(value, arg): try: topic = Topic.objects.get(id=int(value)) user = User.objects.get(id=int(arg)) ...

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

Countless unsuccessful connection attempts on Node.js and socket.io

Good day awesome community at SO! I've been struggling to resolve this issue, and now I'm turning to you for some guidance because I can't seem to figure it out on my own. I have a node.js server that serves an index.html through express, an ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

Tips for transforming every element of an array into its own array using JavaScript or Loadash

Hello, I have an array that looks like this. I am attempting to convert each element into its own array. I tried using lodash's chunk function but was unsuccessful. [ 'Product 1', 'Product 2', 'Product 3', 'Product ...

Blurring isotopes within Google Chrome

While working with isotope in Google Chrome, I noticed that all items have the following CSS code: -webkit-transform: translate3d(properties); In Chrome, every even element [2,4,6,8,10,12,14...] appears blurred, whereas in Firefox everything looks normal ...

What are the specific actions performed on the server and on the client in ReactJS when rendering a component?

I've recently delved into the world of ReactJS, following tutorials and reading the documentation, but I'm still struggling to grasp a fundamental concept about how React actually operates. When a page is served, what exactly occurs behind the s ...

How can I enhance data from an AJAX callback in Mapbox with an additional layer?

With the code snippet below, I am aiming to utilize event data from an API to create a mapbox layer. This layer will be used to place markers and symbols on the map. However, I prefer not to use Mapbox markers as they cause issues with my code. I have suc ...

Extracting JSON data from a string using jQuery

http://localhost/project1/index.php //AJAX region $(function(){ $.ajax({ type : 'GET', url : 'https://jsonplaceholder.typicode.com/posts/1', success : function(data){ console.log('success \n', data); }, error ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...