Duplicate JSON based on specific keys

I am working with two JSON files and I need to match the values from one file to the corresponding keys in the second file.

For instance, let's say I have:

var json1 = {val1: 1, val2:2, val3:3};
var json2 = {val1: 52, val2:56, val7: 7, val5: 5, val3:33};

parseandmatchjson(json1, json2) => {val1: 1, val2:2, val7: 7, val5: 5, val3:3};

The goal is to match keys between the first and second JSON files and replace the values accordingly.

Are there any libraries that can accomplish this task? Alternatively, if you could provide a JavaScript example of how this can be done, that would be greatly appreciated. Thank you.

EDIT: I need to clarify that I require a solution that can handle cases where the structure may not be identical.

For example,

suppose I had

var json1 = {wrapper: 
    {val1: 1, val2: 2}
}
var json2 = {val1: 'without wrapper'}

Is there a library available to achieve a result like this?

{wrapper: {val1: 'without wrapper', val2:2}}

Answer №1

If you're not utilizing jQuery, implement it in the following way:

function mergeJSON(json1, json2) {

    var combined_JSON = {};

    // Deep copy of json1 object literal
    for (var key in json1) {
        combined_JSON[key] = json1[key];
    }

    // Copy other values from json2
    for (var key in json2) {
        if (!json1.hasOwnProperty(key))
            combined_JSON[key] = json2[key];
    }

    return combined_JSON;
}

var json1 = {val1: 1, val2: 2, val3: 3};
var json2 = {val1: 52, val2: 56, val7: 7, val5: 5, val3: 33};
var merged_json = mergeJSON(json1, json2);

If you are using jQuery, the process is simpler

var json1 = {val1: 1, val2: 2, val3: 3};
var json2 = {val1: 52, val2: 56, val7: 7, val5: 5, val3: 33};
var merged_json = $.extend({}, json2, json1);

EDIT

Following the updated question, here is an updated solution to handle nested literals scenario

For your information, in the next solution I will assume that you are not using jQuery since it wasn't mentioned in your question

function mergeNestedJSON(json1, json2) {

    // private function to recursively traverse json objects
    function traverse(object, callback) {
        for (var key in object) {
            // only return leaf nodes
            if ((/boolean|number|string/).test(typeof object[key]))
                callback.apply(this, [object, key, object[key]);  
            // if not base condition, dig deeper into recursion
            if (object[key] !== null && typeof(object[key]) == "object")
                traverse(object[key], callback);
        }
    }

    // create a deep clone copy of json1
    var result = JSON.parse(JSON.stringify(json1));

    // create a flattened version of json2 for optimized lookups
    var flat_json2 = {};
    traverse(json2, function(object, key,value) {
        flat_json2[key] = value;
    });

    // overwrite values in results if they exist in json2
    traverse(result, function(object, key, value) {
        if (typeof flat_json2[key] !== "undefined")
            object[key] =  flat_json2[key];
    });

    return result;    
}

// Now, let's test it
var json1 = {wrapper: {val1: 1, val2: 2}}
var json2 = {val1: 'without wrapper'}
var merged_json = mergeNestedJSON(json1, json2); 

// check the result with a simple alert
alert(JSON.stringify(merged_json));

Here is a JSFiddle Sample click here

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

Component built in React

I'm a newcomer to Jest and JavaScript in general. Recently, I've been working with a js code that involves various components, and now I need to incorporate a Log Out option for the website. Although I have a Log Out component ready, I'm un ...

Error: NullParameterException occurred while using Newtonsoft.Json package to create an object with parameters

When attempting to deserialize a complex object from JSON for a contact, I encountered an issue with an ArgumentNullException. The error stack trace provided is as follows: [ArgumentNullException: Value cannot be null. Parameter name: method] System.D ...

An unhandled error occurred when trying to call _this3.setState - it seems like _this3 is not a

I encountered an error when trying to set the data in state in reactjs. Here's the scenario: I am passing data from a child component to a parent component. In the child component, I call the parent function and change the state value using setState. ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...

Is it true that jQuery and JavaScript operate within separate namespaces?

Within my jQuery code, I am trying to increment a value using the following function: $(document).ready(function(){ var fieldCounter = 0; ... The issue I am facing is that I am unable to access this incremented value from a non-jQuery function. Conver ...

Outputting data from a JSON file onto the console using Javascript

I have a simple question that I am struggling with as a student. Here is the method in question: getMenus: function () { var self=this; $.getJSON('../data/voordeelmenus.json',function(data){ self.menus=$.map(data, function(item, i){ ...

Enhancing the Rendering of React's props.children

I have set up my code like this: // Parent.js class Parent extends React.Component { render() { return { this.props.children } } } // Child.js class Child extends React.Component { render() { let message; const greet = ...

Is it possible to apply withStyles to the output of a function?

Currently, I am attempting to add extra styling to the output of a function that returns one of two components based on specific props. Here is an example: import React from 'react' import { withStyles } from '@material-ui/core/styles' ...

Issue with Google Maps API - Error: google object is undefined

Currently, I am in the process of learning how to develop Google Maps by analyzing some basic examples provided by Google. In my Angular 9 application, I utilize Angular Google Maps to showcase a Google Map. However, as I implement this feature, I encounte ...

Retrieving information from intricate JSON structures using Flutter

I am trying to extract the "title" from this json response Although I can access other data like kind or etag over items, the items array is shown as null. How can I retrieve the title from it? var data = await http.get("https://www.googleapis.com/youtub ...

How can I convert an HTML table into a PDF using TCPDF while ensuring that all content is contained within a single div in PHP?

I have successfully converted my JSON API data into an HTML TABLE format and now I am trying to generate a PDF from this HTML TABLE using TCPDF in PHP. Despite trying various methods related to PDF generation using TCPDF, I am facing issues with my code wh ...

Tips on retrieving and refreshing dynamically generated PHP file echo output within a div

I have a div that I'm refreshing using jQuery every 10 seconds. The content is being read from a PHP file named status.php. Here is the JavaScript and HTML for the div: <script> function autoRefresh_div() { $("#ReloadThis").load("status.php ...

Swap out each addition symbol with a blank space within a given text

I'm currently working on a Typescript project where I need to convert URL parameters into a JSON object. The issue I'm facing is that some values are concatenated with a '+'. How can I replace this symbol with a space? Here's the ...

Combining values from multiple sets of 'radio buttons' in React to get a total

After analyzing the following dataset: const data = [ { id: 1, category: "category1", name: "N/A", price: 0, }, { id: 2, category: "category1", name: "Cheese", ...

Nesting / Mulled / JS - Uploading Files - Form's end is unexpectedly reached

I have successfully implemented the upload file functionality in my Nest.js server application, but I am facing an issue when trying to use it with JavaScript/React. @Post('upload') @UseInterceptors(FileInterceptor('file')) upl ...

What is the best way to retrieve the directory path from a FileReader in Java

Hey there, check out these codes I have for reading the file that the user uploads: function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#myImg' ...

PHP displays the array returned by Ajax as "[object Object],[object Object]"

When working with Jquery, I am creating two arrays - one embedded inside the other. Here is an example of what it looks like: arrayOne = [{name:'a',value:1}, {name:'b',value:2}] var arrayTwo = [{name:'foo',value:'blah&ap ...

Creating fresh JSON data using JQ and bash

I've encountered a challenge trying to generate JSON from scratch using bash. The desired structure should resemble this: { "hosts": { "a_hostname" : { "ips" : [ 1, 2, 3 ] }, {...} } } My fi ...

Ingest JSON child elements using Logstash, structure them appropriately, and load them into Elasticsearch

I have a JSON file that looks like this: "fruits": { "fruit": [ { "id": 1, "label": "test", "tag": "fine", "start": "4", ...

Library for creating custom password input fields with a text type

We are currently facing an issue on our website where autofill is not working correctly due to having two password input fields - one for login and one for the password. Browsers are unable to remember the login information and paste the password into th ...