Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, but I want to keep both sets of data. Thank you.

var json1 = [
  {
    "Column1": "json1",
    "Column2": "json1",
  },
  {
    "Column1": "json1",
    "Column2": "json1",
  }
];
var json2 = [
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

console.log(angular.extend(json1, json2));

The current output is:

[
  {
    "Column1": "json2",
    "Column2": "json2",
  },
  {
    "Column1": "json2",
    "Column2": "json2",
  }
];

However, the desired output is:

[
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  },
  {
    "json1Column1": "json1",
    "json1Column2": "json1",
    "json2Column1": "json2",
    "json2Column2": "json2",
  }
];

Answer №1

To overcome the issue, consider creating a custom function to prefix objects:

function addPrefix(target, prefix){
    var newObj = false;
    if(target.constructor === Array){
        newObj = [];
        for(var i = 0 ; i< target.length; i++){
            item = target[i];
            var itemObj = {}; 
            for(var key in item){
                itemObj[prefix+key] = item[key]; 
            }
            newObj.push(itemObj);         
        }       
    }else{
        newObj = {};
        for(var key in target){
                newObj[prefix+key] = target[key]; 
        }
    }
     return newObj;
}

Instead of using angular.extend, utilize angular.merge for deep property copy. This will prevent properties from the second object being copied into the first. Once you have implemented the custom function, proceed with:

var nJson1=addPrefix(json1,"json1");
var nJson2=addPrefix(json2,"json2");
var merged = angular.merge({},nJson1,nJson2);

Answer №2

An innovative solution involving iteration through keys and items.

const array1 = [{ Name: "John", Age: 25 }, { Name: "Alice", Age: 30 }],
    array2 = [{ City: "New York", Country: "USA" }, { City: "London", Country: "UK" }],
    mergedResult = function (data) {
        let finalArray = [];
        Object.keys(data).forEach(function (key) {
            data[key].forEach(function (item, index) {
                finalArray[index] = finalArray[index] || {};
                Object.keys(item).forEach(function (property) {
                    finalArray[index][key + property] = item[property];
                });
            });
        });
        return finalArray;
    }({ info1: array1, info2: array2 });

document.write('<pre>' + JSON.stringify(mergedResult, null, 4) + '</pre>');

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

Finding the main page URL using PHP within a JavaScript include: A comprehensive guide

I am facing an issue where I have a page with a header include that needs the phone number to change only if the filename of the current page contains a specific word. Typically, for a change outside of an include, the following code would suffice. <? ...

Encountering an "undefined is not an object" error while creating a sinon stub in an Angular

The testing code I am working with is shown below: describe('imagesCtrl', function () { var $rootScope; var $compile; var $log; var $controller; var imagesCtrl; var $q; var images; var vm; beforeEach(module(&apos ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

Initiating an Ajax POST request by clicking a button

I have a button on my webpage that, when clicked, currently prints the value of an element to the console using a basic function. Instead of just printing the value, I want to update my Django view by sending it through a POST request. Here's the cu ...

Managing variables or properties that are not defined in ES6

Currently, I am utilizing Angular and Firebase Firestore in my project. However, the question posed could be relevant to Typescript and pure Javascript as well. The functionality of my application relies heavily on the data retrieved from Firestore. A sim ...

Utilizing Anglar 16's MatTable trackBy feature on FormGroup for identifying unaltered fields

In my application, I am working with a MatTable that has a datasource consisting of AbstractControls (FormGroups) to create an editable table. At the end of each row, there are action buttons for saving or deleting the elements. My goal is to implement tr ...

It is not possible to select a node using a where statement in JSON.net Linq

Looking to locate the node with empUID matching a specific ID. Below is a snippet of JSON data. { "dsShedule": { "ttEmployee": [ { "empUID": 2649, "empNameFirst": "Firstname", "empNam ...

Transferring information using pure JavaScript AJAX and retrieving it through a Node API

On the client side, I have the following code: sendMail(e) { e.preventDefault(); var name = document.getElementById('name').value; var contactReason = document.getElementById('contactReason').value; var email = document ...

Is there a way to dynamically add an option to multiple select boxes and then only redirect the browser if that specific option is chosen using jquery/js?

Presently, this is the code I am working with. The URL validator is specifically included because there was an issue with redirection occurring on any option selected, however, I only want a redirect to happen when the options I add with jQuery are clicked ...

When using Webpack, there may be difficulties resolving relative path import of express static files

I am currently developing an Outlook add-in with an Express server running. To ensure compatibility with Outlook Desktop, I need to transpile JavaScript to ES5 using Webpack. Below is the simplified structure of my project: /public /javascripts ssoAu ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

What is the best way to redirect before displaying a page in Next.js?

Is it possible to redirect a user before rendering a page in Next.js? Currently, my code looks like this: import { useRouter } from 'next/router'; export default function RedirectPage() { const router = useRouter(); router.push('/p ...

PHP sending only a single space in an email

My HTML form works perfectly fine, except for one field! The issue arises with a particular text field that I fill out using a button and a short JavaScript function. Could this be causing a conflict with the PHP code? The problematic text field is: inpu ...

Display a page containing two distinct JSON arrays using Angular

Working with two separate JSON Arrays and incorporating them into a view using ng-repeat. The first JSON array contains text values used to generate fields. ["center", "80mm", "retain", "22pt", "bold", "140%", "18pt", "bold", "140%", "36pt", "11pt", "bol ...

Ways to receive notification during the user's selection of an option by hovering over it

Is there a way to receive an event when a user hovers over a select option? I thought that using the onMouseOver or onDragOver props on the option component would work, but it seems like they only trigger for the parent select component. Below is a simpli ...

When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue: const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im; re.test(control.valu ...

Obtain a variety of image sets nested within an array of content

My goal is to gather all available images from user photos with the same photo title and timestamp, store them in an array, and display the total number of images posted under a specific post ID. Currently, the post is being inserted correctly, but when u ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...