combine two JSON objects

Similar Question:
Combining and sorting two json objects

I have a pair of JSON objects

[
{"name": "Graduation"},
{"name": "Post Graduation"}
]

and another one that is identical

[
{"name": "first sem"},
{"name": "second sem"},
{"name": "third sem"}
]

How can I merge these two JSON objects into one, like this:

[
{"name": "Graduation"},
{"name": "Post Graduation"},
{"name": "first sem"},
{"name": "second sem"},
{"name": "third sem"}
]

I attempted to do this using the following code:

_this.model = new qualification();
_this.model1 = new sems();
 jsondata = _this.model.toJSON();
 jsonData = _.extend(_this.model1.toJSON(),jsonData)

The resulting JSON has conflicting keys

I also tried
var result = _.union([jsonData1],[jsonData2]);
console.log(JSON.stringify(result));

Even when using concat, the output looks like this:

[{"0":{"name":"first sem"},"1":{"name":"second sem"},"2":{"name":"third sem"}},{"0":{"name":"Graduation"},"1":{"name":"Post Graduation"}}],

Answer №1

When dealing with arrays instead of objects, it's best to use _.union. Here's how you can achieve union between two arrays:

_.union(*array);

Snippet

var A = [
    {
    "name": "Graduation"},
{
    "name": "Post Graduation"}
];

var B = [
    {
    "name": "first sem"},
{
    "name": "second sem"},
{
    "name": "third sem"}
];

console.log(_.union(A,B)​);​​​​

Live Demo

http://jsfiddle.net/7FkWs/

Answer №2

When referring to "JSON objects," I am assuming you are referring to JavaScript objects, which are essentially arrays. These can be concatenated together using the Array#concat() method:

var array1 = [{"name":"Graduation"}, {"name":"Post Graduation"}];
var array2 = [{"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];
var combinedArray = array1.concat(array2);
combinedArray; // [{"name":"Graduation"}, {"name":"Post Graduation"}, {"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];

If these objects are actually serialized JSON strings, you can parse them and then concatenate as follows:

var parsedArray1 = JSON.parse(array1).concat(JSON.parse(array2));
parsedArray1; // [{"name":"Graduation"}, {"name":"Post Graduation"}, {"name":"first sem"}, {"name":"second sem"}, {"name":"third sem"}];

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

React - Issues with passing props correctly from mapped array to child component

I am currently working on a dashboard component that showcases rendered previews and code for HTML snippets. Within this dashboard component, I am utilizing the .map method to iterate through an array of snippets. Each snippet will have a pre-existing dele ...

Tips for adjusting the dimensions of a cube using keyboard shortcuts:

Adjusting the cube size involves keeping one face stationary while others move and change in position or dimension. The height, depth, and width must be expanded or contracted based on user input from the keyboard. I have managed to create a cube, but so ...

Is there a way to store MongoDB collections in an array when integrating Mongoose with ExpressJS?

I am looking to extract collections from a MongoDB database and store them in an array, essentially creating an array of JavaScript objects. ...

Sending a POST request to Mailchimp via Express using React: A step-by-step guide

I'm currently working on a project where users can sign up for a new membership through a form in React and have their information added to the Mailchimp member list via my Express server. However, I've encountered a CORS error and am unsure if I ...

What is the reason behind the "import statement error" that occurs during yup validation?

When running our code, we are encountering the following error: "Module not found: Can't resolve '@hookform/resolvers/yup'" ...

Issue with redux that causes components to not re-render when they are placed inside an "OnClick" event

Apologies for my limited English skills, but I am currently working with React and Redux. Here is the React code: import gsap from "gsap"; import { useGSAP } from "@gsap/react"; import githubLogo from "../assets/github.png"; i ...

Harnessing the power of jQuery.load() and ajax dataFilter() for dynamic content loading

Recently, I encountered a situation where I was utilizing jQuery.load() to bring in the content of an HTML page into a lightbox. The beauty of the load function lies in its ability to transform complete HTML pages into neat HTML fragments that can easily b ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

MVC3: Awaiting File Download with Progress Indicator

After completing my research and looking through similar threads, I still haven't found a satisfactory answer to my problem. I am currently working with MVC3, C#, and the Razor View Engine. The situation I'm dealing with is quite straightforwar ...

utilizing a returned list from a controller in an ajax request

When using an ajax call to store data in a database and the controller returns a list of commentObjects, how can this list be accessed in a JSP file? function StoreCommentAndRefreshCommentList(e) { var commentData = document.getElementById(ActualComme ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

Update the URL once a form has been successfully submitted using AJAX with a GET request

I am trying to update the current URL after submitting a form using an AJAX GET request. Previously, I attempted to utilize history.pushState(null, null, url+'?'+form.serialize()) and it did work fine. However, the issue arises where only a port ...

What is the best way to implement a seamless left-to-right sliding effect for my side navigation using CSS and Javascript?

I am currently working on creating a CSS and JavaScript side navigation. Below is the code that I have implemented so far: var nav = document.getElementById('nav'); function show(){ nav.style.display = "block"; } .side-nav{ background-color:bl ...

The Facebook Javascript SDK may encounter an OAuthException#2500, indicating that an active access token is required to access information about the current user

window.fbAsyncInit = function() { FB.init({ appId : '154776817xxxxxxx', xfbml : true, version : 'v2.1' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.g ...

Guide to refreshing extensive dataset using MySQL migration scripts

We are in the process of developing a Nodejs application for a client who has requested that we use migration scripts to streamline updating the production database. As someone new to MySQL, I am struggling with how to update table contents using only MySQ ...

The browser has blocked access to XMLHttpRequest from a specific origin due to the absence of the 'Access-Control-Allow-Origin' header in the requested resource

After developing an Asp.Net Core 3.1 API and deploying it on the server through IIS, everything worked fine when sending GET/POST requests from Postman or a browser. However, I encountered an error with the following code: $.ajax({ type: 'GET' ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Issue with uploading files on Android devices in Laravel and Vue JS

My Laravel/Vue JS web app allows users to upload files and photos. Everything runs smoothly except when accessed on Android devices, where the axios call seems to get stuck indefinitely. Below is the code snippet causing the issue: Vue JS component <t ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...