Merging JSON Objects with identical numbers of key-value pairs, and combining the main key values

I have a JSON objects in an old parser program that I wrote years ago.

{"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"}

{"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""}

Originally, the above entry was meant to be a single record. However, due to line wrapping, the parser is treating them as separate records.

I attempted to map the objects by converting them into an array, but it resulted in the following JSON object:

{"Date":"19/02/16"}{"Date":""},{"Narration":"NEFT DR-BARB0PIMPAL-Govt. NE"}{"Narration":"TBANK, MUM-N050160130709970"},{"Chq":{"/Ref":{"No":{"":"N050160130709970"}}}}{"Chq":{"/Ref":{"No":{"":""}}}},{"Value Dt":"19/02/16"}{"Value Dt":""},{"Withdrawal Amt":{"":"8,000.00"}}{"Withdrawal Amt":{"":""}},{"Deposit Amt":{"":""}}{"Deposit Amt":{"":""}},{"Closing Balance":"24,114.95"}{"Closing Balance":""}

What I need is to merge/combine this data into a single array or object while keeping the main keys intact and appending values together (with the second object being discarded thereafter).

For instance:

{"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt.NETBANK","Chq":{"/Ref":{"No":{"":"N050160130709970MUM-N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"}

Is there a way to directly merge/combine the source JSON Object or merge the arrays to achieve the desired outcome?

Answer №1

In order to merge split objects, it is crucial to have the correct order of these objects. Assuming you have an array of JavaScript objects parsed from JSON format.

Additionally, identifying a record that continues from the previous one can be done by checking for an empty balance field (adjust as necessary).

Below is the code snippet to effectively merge these split objects:

function mergeSplitObjects(arr) {
    return arr.filter( (curr, i) => {
        // Is this object meant to be merged with the previous one?
        if (curr["Closing Balance"] !== "") { // Adjust condition accordingly
            return true; // It's a valid record
        }
        arr[i-1]["Narration"] += curr["Narration"]; // Merge and remove current item
    });
}

// Sample data containing 3 records. The first two should be merged
let arr = [
    {"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""},
    {"Date":"20/02/16","Narration":"ATM NYC 13","Chq":{"/Ref":{"No":{"":"N050160130709971"}}},"Value Dt":"20/02/16","Withdrawal Amt":{"":"1,000.00"},"Deposit Amt":{"":""},"Closing Balance":"23,114.95"},
];
arr = mergeSplitObjects(arr);

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

A function similar to Object.assign could be utilized in this scenario.

In accordance with Trincot's viewpoint, the presence of Closing Balance serves as a signal for merging records.

var splitRegExp = /[a-z],\s*[a-z]/gi;
function deepMergingAssign(obj /*, sourceObjects*/){
    'use strict';
    if (obj == null) throw new TypeError('Cannot convert undefined or null to object');
    var final = Object(obj);
    [].slice.call(arguments, 1).forEach(function(arg){
        if(arg != null) {
            for(var prop in arg) {
                if (typeof arg[prop] === 'object'&&typeof final[prop] === 'object') {
                    // recursively call this function
                    arg[prop] = deepMergingAssign(final[prop],arg[prop]);
                    delete arg[prop]
                }
                else if(Object.prototype.hasOwnProperty.call(arg,prop)) {
                    // append the new values to the existing value.
                    var currentValue = final[prop].split(splitRegExp);
                    var incomingValue = arg[prop].split(splitRegExp);
                    incomingValue.forEach( function(val){
                        if (val! == '' && currentValue.indexOf(val) === -1) currentValue.push(val);
                    });
                    final[prop] = currentValue.join(', ');
                }
            }
        }
    });
    return final;
}

function mergeRecords(records){
    var toMerge = [];
    var mergedData = []
    for (var i=0; i<records.length; i++){
        // Modify this condition as per requirements
        if (records[i]['Closing Balance'] !== '' && toMerge.length>0){
            // Formulate a merged record and reset the toMerge array
            mergedData.push(deepMergingAssign.apply(null, toMerge));
            toMerge = [records[i]];
        }
        else {
            // Merge the current record with the preceding one
            toMerge.push(records[i]);
        }
    }
    // Merge the last set of records stored in the array
    mergedData.push(deepMergingAssign.apply(null, toMerge));

    return mergedData;
}

var allRecords = [
    {"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""},
    {"Date":"21/02/16","Narration":"TBANK","Chq":{"/Ref":{"No":{"":"N050160130709971"}}},"Value Dt":"21/02/16","Withdrawal Amt":{"":""},"Deposit Amt":{"":"2,000.00"},"Closing Balance":"26,114.95"},
    {"Date":"22/02/16","Narration":"TBANK","Chq":{"/Ref":{"No":{"":"N050160130709972"}}},"Value Dt":"22/02/16","Withdrawal Amt":{"":"5,750.00"},"Deposit Amt":{"":"1,000.00"},"Closing Balance":"21,364.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709972","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""}
]

var merged = mergeRecords(allRecords);
/* [
    record 1+2,
    record 3,
    record 4+5
   ] */

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

How to overcome the issue of Bootstrap Modal blocking link functionality?

My website is built using Bootstrap 4. I have a navigation menu where a modal drops down when the MENU button is clicked. However, I am facing an issue with activating links within the modal. I've tried everything but the links just won't work. I ...

What is the best way to apply margins to a nested div element in relation to its parent div element using CSS?

My Coding Dilemma: #b { width: 700px; height: 150px; margin-top: 10%; margin-left: 20%; text-align: center; border: 2px solid black; } .block { width : 10%; height : 10%; border: 2px solid black; padding: 40px 40px; margin: inheri ...

Adding unique parameters to a rails form

As a newcomer to web development, I am facing the following challenge: I have three models in my application: products class Product < ApplicationRecord has_and_belongs_to_many :steps end steps class Step < ApplicationRecord has_and_belongs_ ...

How to eliminate numerous elements from a bash array using various patterns

Here's the scenario: INTERFACES=($(ip -o link show | awk -F': ' '{print $2}')) This code gives me an array of interfaces, but I want to remove the loopback and tun adapters from it. INTERFACES=(${INTERFACES[@]/lo/}) INTERFACES=( ...

Finding the average of a column within a PHP array

I have a text file with tab-delimited data that needs to be processed. You can access the file here: I've successfully converted the data into an array using this PHP script: However, I'm struggling to figure out how to calculate the average fo ...

Slightly unsure regarding Gzip compression in relation to my web application

Apologies in advance for my beginner question, but I haven't been able to find a thorough explanation on this topic. I recently developed a web app using React and utilized an NPM plugin to generate standard and Gzip compressed versions of the main.js ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

Display the button only if the specified condition aligns with the input data

I am working on a project where I have an input text field that retrieves data from a database using a combination of JavaScript and PHP. get.html is responsible for fetching the data through JavaScript. function showUser(str) { if (str == "") { ...

Avoiding Repetition in ListView in Android by Filtering JSON Data with EditText

I have been working on a search feature that utilizes EditText, ListView, JSON, and a Database. The goal is to update the ListView every time the user inputs text into the EditText field. I am using a MySQL database with a SELECT query using the LIKE met ...

Reloading a DIV element on the website causes any additional OnClick event handlers to be disabled, along with

My HTML structure looks like this: <div class="inner-content"> <div class="catalogue" style="display: none;"> <div class="wrapper"> <!-- some dom here --> <button type="button" id="updateCatal ...

Convert the property that starts with XX from XML to JSON

I am currently working on a function that looks like this request.execute('[someSP].[spSomeSP]', function(err, dataset) { _.map(dataset, function(items) { console.log(items); }); }); When the _.map(...) is executed, it retu ...

Explanation of if-statements and the ability to read if conditions from another object such as String[] (Dynamic If)

I am dealing with a complex object named "input" that contains numerous fields, and I need to check for null values in each field. Currently, my code looks like this: if ((input.getAction().isEmpty() || input.getAction().isBlank()) || (input.getSub ...

Pandoc fails to display SVG images when converting HTML to DOCX

I am currently utilizing pandoc for the conversion of a standalone html file (without external dependencies), incorporating all necessary css and js within the html itself. Within this HTML document, there are several svg graphs that have been generated th ...

Can you merge the values between two arrays of objects by counting them and combining them into a single array?

I'm faced with an array conundrum categories: [ { name: 'category1', items: 0, }, { name: 'category2', items: 0, }, { name: 'category3', items: 0, }, ] And then there's this separate ar ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

What steps can I take to address the problem in iOS 17 where sound is coming from the earpiece instead of the speaker during camera activation?

I have a Progressive Web App where I use the getUserMedia() API to access the camera and HTML audio tags for handling media content. However, ever since updating to iOS 17, I've faced an issue where audio plays through the earpiece instead of the medi ...

Tips for maintaining active javascript content within a WebView while navigating to a different page

When working in a WebView, I have the option to either load JavaScript code using view.stringByEvaluatingJavaScriptFromString or by directly loading it into the JS context retrieved via view.mainFrame.javaScriptContext. The challenge arises when I navigat ...

Steps to create a 3D mesh graph using three 1D arrays in Matlab

Creating a 3D mesh graph in Matlab with three 1-dimensional arrays: The arrays are as follows: x={1,2,3,4,5} y={6,7,8,9,10} z=(11,12,13,14,15} Click here for image reference. Please provide Matlab code for the Mesh Graph. Most resources available foc ...

Tips on saving content that changes automatically

I am curious about the best way to store dynamically displayed HTML content. For example, when a certain element is clicked on a website, I want text to appear elsewhere on the page. One idea I had was to create a variable in a JavaScript/jQuery script to ...

React function component often uses the "this" keyword in order to

When looking at the code below, I encountered an error stating that handleClick is not defined. I attempted to use onClick={this.handleClick} but it did not resolve the issue. How can I properly access the handleClick function for the onClick event of th ...