Combining JSON data in Typescript using the merge method

Is there a way to effectively merge JSON objects in such a manner that simple values (strings, numbers, booleans, etc) get overridden when keys match, but when dealing with complex values (arrays and objects), different outcomes apply? 1.) For simple arrays of strings, the strings should be merged, while for objects, a recursive solution should be implemented. 2.) When dealing with objects, again, a recursive solution is necessary.

I have experimented with various npm packages, but I am still on the lookout for the ideal solution.

const jsonA = {
    Results: [
        {
            PgId: "pg1",
            Entities: [
                {
                    EntityName: "Customer",
                    Subjects: [
                        {
                            first_name: "Mark",
                            last_name: "woodruff",
                            location: "tenino"
                        },
                        {
                            first_name: "helen1",
                            last_name: "mclean1",
                            location: "washington1"
                        }
                    ]
                }
            ]
        }
    ],
    pets: ['Cat', 'Parrot'],
    isComplete: false
}

const jsonB = {
    Results: [
        {
            PgId: "pg1",
            Entities: [
                {
                    EntityName: "Customer",
                    Subjects: [
                        {
                            first_name: "Mark",
                            last_name: "woodruff",
                            location: "tenino"
                        },
                        {
                            first_name: "helen",
                            last_name: "mclean",
                            location: "washington"
                        }
                    ]
                }
            ]
        }
    ],
    pets: ['Dog'],
    isComplete: true
}

EXPECTED OUTPUT :

const mergedBA_B_overrides_A = {
    Results: [
        {
            PgId: "pg1",
            Entities: [
                {
                    EntityName: "Customer",
                    Subjects: [
                        {
                            first_name: "Mark",
                            last_name: "woodruff",
                            location: "tenino"
                        },
                        {
                            first_name: "helen",
                            last_name: "mclean",
                            location: "washington"
                        },
                        {
                            first_name: "helen1",
                            last_name: "mclean1",
                            location: "washington"
                        }
                    ]
                }
            ]
        }
    ],
    pets: ['Dog','Cat', 'Parrot'],
    isComplete: true
}

Answer №1

To effectively merge values from one object to another, you must recursively iterate through the properties of the object and replace the source values with the target values.

If you're looking for a solution, you can search 'github gist javascript mergedeep' to find helpful resources:

It's important to be cautious when merging values in arrays using the provided solution. If you need to handle arrays as well as objects, consider implementing a solution like this one:

I have personally utilized similar solutions to both of these methods.

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

Utilizing Python for extracting text from dynamically generated web pages with JavaScript

Is there a way to write a script in Linux that can extract text from a page generated by Javascript, specifically using etherpad (for example, http://www.board.net)? I have not been able to find an existing tool that fits my needs, such as lynx which doesn ...

JavaScript: Retrieving the coordinates of the visible area of an element

Is there a way to calculate the visible area of an element on the screen, taking into account any hidden parts due to CSS properties like overflow: scroll and position: absolute? The goal is to create a function called getVisiblePart(el) that will return ...

Tips for securely utilizing a javascript API without exposing your API key

Newbie alert! I am currently working on an app that utilizes Here's Geocoding REST API through node.js with express. (I made sure to keep my api key hidden on the server side to prevent exposure to clients.) However, I have come to realize that in or ...

Styling for jQuery (and javascript) code snippets

Is it just me, or does anyone else feel like they want to write javascript and jQuery in a different structure after making numerous mistakes with curly brackets and parentheses? I wish there was an IDE that could automatically collapse the code back into ...

Icons not appearing in TinyMce

Currently, I am utilizing Laravel in combination with Blade and Vue.js, specifically the tinymce-wrapper @tinymce/tinymce-vue. The Issue: Following a transition from cloud to self-hosted, TinyMce (version 5.7.0) is not displaying icons as expected. <te ...

Trigger an AJAX request by clicking on a specific div element

My goal is to trigger an AJAX call when a user clicks on a location marker in a Google map integration. The function info_window_content, available at this link: http://jsfiddle.net/6xw2y/, is responsible for creating the necessary div elements within the ...

How to send parameters to Bootstrap modal using a hyperlink

I need help confirming the deletion of a datatable row using a Bootstrap modal dialog. When a user clicks on the delete link, I want a modal to appear asking for confirmation. Here is my code: <c:forEach items="${equipes}" var="equ"> ...

Dealing with 404 errors in Apache mod_wsgi Flask when handling large json files

I have a Flask application set up with mod_wsgi on Apache. Within the app, I have a series of charts that retrieve data (~2Mb per file) from a static route @app.route('/data/<experiment_id>/<sensors>.json, where I utilize the JSON mimetype ...

Adding a refresh feature to ui-sref in markup

Is there a way to include the reload option in a ui-sref markup without using the javascript function directly? <a ui-sref="app.editPost({new:true}, {reload:true})">new post</a> I've tried this approach, but it doesn't seem to be wo ...

Unable to access account with Passport.js after cookie expiration

Currently, I am utilizing Passport JS as my authentication middleware with a local strategy. The authentication process works smoothly until the cookie expires, and then I am unable to login. passport.use(new LocalStrategy({ usernameField: 'email ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...

Having trouble configuring a basic express server to host a static JavaScript file

Struggling to set up a basic Express server with accompanying HTML and JS files. Despite multiple attempts, I can't get the JS file to properly load. index.js: const express = require("express"); const app = express(); const path = require ...

I am on a quest to locate a specific key within an array of objects and then validate it using Regex

I've been struggling with this for over 3 days and still haven't found a solution. It feels like trying to find a needle in a haystack, but I'm determined to figure it out. My goal is to search for a specific key in an array of objects and ...

How to Condense a JSON Array using Google Apps Script

My current task involves flattening the JSON file provided below into an array structure: { "@context": "http://schema.org", "@type": "EventReservation", "reservationNumber": "IO12345", "underName": "John Smith", "reservationFor": [{ "@type" ...

What is the best way to connect socket.io to multiple instances of HTTPServer?

My Express server is set up to listen on both HTTP and HTTPS: Above, you can see the code snippet where I create the server instances for both HTTP and HTTPS protocols using Express. Currently, I am facing an issue with socket.io as it only listens to on ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Warning: An alert has been triggered while generating files using create-react-app

npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e896999d9c81849ba8dbccd1ded8d4cfdcd0c59bc6cbca">[email protected]</a> requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= ...

When the React.js app is launched on the server, it appears as a blank page, but functions perfectly when accessed locally

When I launch my React.js frontend locally with npm start, it runs smoothly. However, when attempting to run it on the server by using npm install followed by nom start, a blank page appears. Upon inspecting the public folder, I found the following conten ...

Examining the dimensions of a div element in AngularJS

As I delve deeper into understanding AngularJS and tackling the intricacies of how $watch operates, a specific scenario has caught my attention. I want to monitor and track changes in the dimensions of the div element with an ID of "area". My intention is ...

Path expression is not valid as it attempts to access an element

When attempting to modify a single element in an array, I encounter the error message Invalid path expression near attempt to access element. Interestingly, this issue only arises when the array is obtained from --rawInput. For instance: # input: [ 1, 0 ...