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

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

Having trouble dynamically assigning the ng-model attribute

I am trying to populate the ArrayINeed array, which is the object I need to pass back to the API call. Currently, I am getting undefined for "ConfirmedTrackingReferenceNumbers": Dc.ArrayINeed. Despite researching various posts online and on SO, I have been ...

How to incorporate "selectAllow" when dealing with dates in FullCalendar

I've been attempting to restrict user selection between two specific dates, but so far I haven't been able to make it work. The only way I have managed to do it is by following the routine specified in the businessHours documentation. Is there a ...

Is there a way to access the target element containing the ui-view attribute in ui-router when a state transition occurs?

Below is an example where the target element used to load templates for state1 and state2 has an id of "target". When a state change occurs, I need to access this element in order to add additional classes (such as a loading indicator) using one of the sta ...

Integration of AngularJS with PHP for Seamless User Authentication

As a newcomer to angularjs, I find the Login Process a bit confusing. Every time I log in, I'm automatically redirected to a specific page that is already set in the code. I just want a simple check to see if the user is logged in. If they are, then ...

Tips on implementing CSS to the subpar class in Vuejs

I am working on an HTML file that operates with button in Vue.js. The v-bind:class can be utilized for a single tag as shown below. It disappears based on the boolean value of bool data. <h3 v-bind:class="{active: bool}">{{counter.document}}&l ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

How can you display a set of components in React using TypeScript?

I'm currently working on rendering an array of JSX Components. I've identified two possible methods to achieve this. Method one (current approach): Create the array as an object type that stores the component properties and then build the JSX co ...

Click on the dropdown item in the Bootstrap btn-group dropdown

I am interested in clicking the dropdown item within the btn-group and triggering an alert message. This is the HTML code I have: <td> <div class="btn-group" role="group"> <button id="btnGroupVerticalDrop2" type="button" class= ...

The Angular JS Factory fails to send data back to the controller

When I call the method getPopularMovies in my factory using the controller, it returns undefined. I'm not sure what mistake I've made here. Please help me figure it out. My Factory angular.module('ngMovies').factory('moviesFactor ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

How to update an array in MongoDB with PyMongo

Currently working on a RESTful API in Python utilizing PyMongo, and encountering an interesting scenario with my Mongo object: { id: "123", items: ["a", "b", "c"] } My objective is to update the 'items' array to: ["d", "e", "f"] Seeking advic ...

Can the renderWith function of a column in angular-datatables retrieve a value from a promise?

Can I trigger a call to a service or filter that retrieves a promise from the renderWith() function of a column? When I attempt this, the result always appears as "[object Object]". vm.dtInstance = {}; vm.dtOptions = DTOptionsBuilder.fromFnPromise(MySe ...

Challenge encountered while processing JSON data

I've searched through various threads and tutorials, but I'm still stuck on this issue! I have two JSON responses that need to be utilized in separate functions: 1st (single element) Need to extract "Intention_category" and "count" Data: { " ...

res.send No data being transmitted - in the realm of Express.js

I'm currently developing a calculator app using Express.js, but I seem to be encountering an issue with the res.send Method as I am not getting any response. My expectation is for my webpage to display the sum from the calculator.js file. Nodemon is a ...

The ExpressJS EJS issue arises when trying to access a property that is undefined

I'm new to NodeJS and seeking assistance. I am working on a website where users can promote their virtual conferences for others to see. I have set up a form with the POST method, where the data gets pushed into an array and then displayed in an EJS f ...

Attempting to concatenate a missing closing curly brace to an invalid JSON entity

There is a json file with a line missing a closing bracket ('}') at the end. Example input: {"title_text": "Malformed JSON", "createdAt": "2020-10-17T02:56:51+0700", "text": "Some post conte ...

When converting JSON to a pandas DataFrame in Python, all fields are displayed as type 'Object'

Currently, I am using pandas to read a json string into a data frame. When I check the dataframe info, all columns are displaying as 'Object' data type instead of their actual data types. My intention was to loop through the columns and apply cer ...