Combining JSON Data with Fuzzy Matching

I have a JSON data structure that looks like this

{
"array": {

"InvestmentsDeposits": {

            "NAME": "Investments & Deposits",
            "PARENT": [
                {
                    "CONTENT_ID": "Promotions",
                    "DISPLAY_ORDER": 3,
                    "PATH": "/Promotions"
                }
            ]
        },
        "InvestmentsDeposits$$$d": {

            "NAME": "Deposits",

            "PARENT": [
             {
                "CONTENT_ID": "NewPromotion",
                 "text" : "newtext"
              }
            ]
    }

    }
    }

I am seeking to find and merge similar data using fuzzy logic. For example, InvestmentsDeposits and InvestmentsDeposits$$$d should be merged because they are closely matched in name

My objective is to accomplish this task using javascript

Currently, I can ensure that the source data always contains $$$d at the end to facilitate merging with target data lacking $$$d, such as InvestmentDeposits.

The resulting merged content should resemble this

{
    "array": {

    "InvestmentsDeposits": {

                "NAME": "Deposits",
                "PARENT": [
                    {
                        "CONTENT_ID": "NewPromotion",
                        "DISPLAY_ORDER": 3,
                        "PATH": "/Promotions"
                         "text": "newtext"
                    }
                ]
            }

        }
    }

Any assistance on this matter?

Here's what I have attempted thus far

var json0 = {

"InvestmentsDeposits": {

            "NAME": "Investments & Deposits",
            "PARENT": [
                {
                    "CONTENT_ID": "Promotions",
                    "DISPLAY_ORDER": 3,
                    "PATH": "/Promotions"
                }
            ]
            }
            };

var json1 =

{

"InvestmentsDeposits$$$d": {

            "NAME": "Deposits",

            "PARENT": [
             {
                "CONTENT_ID": "NewPromotion",
                 "text" : "newtext"
              }
            ]
    }

    };


    // Merge object2 into object1, recursively

$.extend( true, json0, json1 );

I am able to merge the data if I can separate the InvestmentDeposits and InvestmentDeposits$$$d into two distinct JSON objects, but how can I split and relocate the $$$d data into another object for the jquery extend method to work properly?

Answer №1

Utilize the Object.keys() method to identify the keys of an object and determine which data needs to be transferred. By comparing the first key with the others, you can locate matches and then eliminate those keys from consideration until all are processed. Below is a demonstration using a similar object structure.

    var dat = {
        "InvestmentsDeposits": {
            "NAME": "Investments & Deposits",
            "CONTENT_ID": "Promotions",
            "DISPLAY_ORDER": 3,
            "PATH": "/Promotions"
        }, "InvestmentsDeposits$$$d": {
            "NAME": "Deposits",
            "CONTENT_ID": "NewPromotion",
             "text" : "newtext"
        },
        "NotLikeTheOthers": {
            "Um": "Yeah."
        }
    
    };
    var result = {}; // Merged object will be stored here
    var keys = Object.keys(dat); // Holds the keys
    while(keys.length) {
        var i=1;
        for(; i<keys.length; i++) { // Identifying matches
            if(keys[0] == keys[i] + '$$$d') { // Match type 1
                result[keys[i]] = dat[keys[i]]; // Copy original values
                for(var j in dat[keys[0]]) { // Updating values
                    result[keys[i]][j] = dat[keys[0]][j];
                }
                keys.splice(i,1);
                keys.shift();
                i = 0;
                break;
            } else if(keys[i] == keys[0] + '$$$d') { // Reversed match
                result[keys[0]] = dat[keys[0]];
                for(var j in dat[keys[i]]) {
                    result[keys[0]][j] = dat[keys[i]][j];
                }
                keys.splice(i,1);
                keys.shift();
                i = 0;
                break;
            }
        }
        if(i > 0) { // No match found
            result[keys[0]] = dat[keys[0]];
            keys.shift();
        }
    }
    alert(JSON.stringify(result));

Note that Object.keys() is compatible with IE9+.

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

By checking the active box and completing the fields, the button will be activated

I'm currently working on a form that requires all fields to be filled out and the acceptance checkbox to be checked before the Submit button becomes active. If any entry or the checkbox is subsequently removed, the button should become inactive again. ...

Refreshing the form fields and storing the information using AngularJS

I have successfully implemented a basic form using AngularJS. The issue I am facing is that even after the user enters their details and submits the form, the values remain in the input fields. My goal is to store the details of multiple fields in the con ...

Javascript - Conceal a Dynamic Div Depending on its Text

I have a unique table that generates dynamic Divs with ID's that count as they are created in the following format: <div id="dgpCheckDiv10_0"> <input Delete </div> <div id="dgpCheckDiv10_1"> text2 </div> Some of t ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Module 'js' not found

Upon adding a request, I encountered this error message. I attempted npm install js and added var js = require("js") in my app.js file, but unfortunately it did not resolve the issue. My express server is running on localhost. Error: Cannot find module &a ...

Javascript will not recognize or interpret PHP's HTML tags

When PHP sends HTML strings to HTML through AJAX wrapped in <p class="select"></p> tags, the CSS reads the class perfectly. However, JavaScript/jQuery does not seem to work as expected. Even when trying to parse <p onclick="function()">&l ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

Error: Parse Error - Invalid character detected during JSON parsing in C#

I am currently in the process of deciphering my jwt token. A recent addition I made to it is the inclusion of a new object named "userGroupList". This object is essentially a class that is converted into a string using JsonConvert.SerializeObject. However, ...

Implement a function within a v-for iteration

Currently, I am facing a challenge in Vue 3 while attempting to design a menu with categories and corresponding subcategories. The objective is that upon clicking on a category, only the specific subcategories related to that category should be displayed b ...

Utilizing JSON data for efficient React component rendering

As a newcomer to React, I am currently in the process of constructing a dashboard that showcases data from three different sensors. The information regarding these sensors is stored in a single JSON file where each sensor has its own ID and name. This JSON ...

The automatic CSS cookie bar functions smoothly, but could benefit from a small delay

I successfully added a pure CSS cookie bar to my website, but there is a slight issue. When entering the site, the cookie bar is the first thing that appears, and then it goes up and down before settling at the end. How can I make my cookie bar only go do ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

Utilizing Google Chrome Extension: Sharing variables between injected scripts via chrome.tabs.executeScript to another script injected in a similar manner

Can anyone help me with a coding challenge? I have two scripts injected in my popup.js and I need to make a variable defined in one script accessible to the other. Here's how I'm injecting the scripts: let sortFunction = function (goSortParam) { ...

Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#. One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while ...

Ways to rearrange div elements using JavaScript

I need assistance with reordering div elements using JavaScript, as I am unsure of how to accomplish this task. Specifically, I have two divs implemented in HTML, and I would like the div with id="navigation" to appear after the div with class="row subhea ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

Having trouble with changing the state within an AngularJS (Ionic Framework) controller?

My goal is to switch views within the Search controller after receiving search results from the server through $http. However, my current approach doesn't seem to be working as intended. I also need to pass the response to the new view for displaying ...

The navbar toggler icon is not displaying

<header class="container"> <div class="container pt-3 col-md-5 col-sm-5 col-xs-6 text-center"> <a href="#" class="site-logo"><img src="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" ...

An unexpected punctuation token «(» was encountered instead of the expected punctuation when generating a chunk using UglifyJS

I encountered an error while attempting to perform a production build using webpack version 2.2.1: > cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress Hash: 7bb2cdb98aab2f36f7e1 ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...