Guide to merging two JSON objects

I have two JavaScript objects as shown below:

const objOne = {
  "firstname": "xzxz",
  "lastname": "xzxzxzx"
};

const objTwo  = {
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
};

I would like to merge them into a single object structure, combining the properties.

{
  "firstname": "xzxz",
  "lastname": "xzxzxzx",
  "title": [
    {
      "name": "foo",
      "table": "First"
    },
    {
      "name": "bar",
      "table": "Second"
    }
  ]
}

My attempted solution so far is as follows:

   let result = [];
     results.push(objOne);
     results.push(objTwo);

However, this approach creates an array with both objects instead of merging their properties.

[
  {
    "firstname": "xzxz",
    "lastname": "xzxzxzx"
  },
  {
    "title": [
      {
        "name": "foo",
        "table": "First"
      },
      {
        "name": "bar",
        "table": "Second"
      }
    ]
  }
]

Answer №1

const person = {
  "name": "John",
  "age": 30
};

const address = {
  "city": "New York",
  "state": "NY"
};

const details = { ...person, ...address };
console.log(details);

Answer №2

A convenient method is using Object.entries() to transform objects into arrays, then utilizing Object.fromEntries() to convert them back into objects.

const person = {
  "name": "John",
  "age": 30
};

const address = {
  "city": "New York",
  "country": "USA"
};

const merged = Object.fromEntries(
  Object.entries(person)
  .concat(Object.entries(address))
);

console.log(merged);

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

Issue with Spring JPA: Foreign keys missing from response

I have a database containing entities in a parent-child relationship. When querying the child table to retrieve all rows, only the non-foreign key fields are returned in the JSON response. Can someone assist me in including the foreign key in the JSON resp ...

Having trouble retrieving the selected date from the Material-Ui datepicker after the first selection

I am facing an issue with the material-ui dateandtimepicker where I am unable to retrieve the date value on the first select. The value only shows up after the second click, and it's always the previous one. Is there a way to convert the date to a for ...

The header logo disappears when the Vue.js id is added to the body

Currently, I am in the process of transitioning landing page templates from Angular.js to Vue.js version 3. During this process, I have encountered an issue where the script is being applied to the entire body instead of a specific element. The problem ar ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

Error encountered: A missing semicolon was detected before a statement while executing code within a for

Although this question may have already been asked, I am struggling to understand why it is not working as expected. I simply want to increment the markers array within a for loop and then add each marker to the vector source using vectorSource.addFeature ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

What will be the quickest and most reliable trigger - matchMedia, window.resize, orientationchange, or perhaps both combined?

I am trying to trigger a function when a user rotates their device and I'm seeking advice on which event would be most effective for this purpose. In your experience, which event do you recommend that will call the function quickly and consistently? I ...

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

Python troubleshooting: Understanding 2D array indexing

Working on a project involving 2D arrays and random sequence generation. The goal is to create 10 lists with 6 unique integers each, ranging from 0 to 100, stored in a 2D array. However, I am encountering errors related to list index out of range that I ...

When working with multiple states in React, the toggle does not update on click when using setState

As a beginner in React JS, I have been learning and experimenting with state management. Initially, I successfully used setState to change the state. However, I encountered an issue when attempting to work with multiple states simultaneously – it didn&ap ...

The setting for the background color of the chart area in chartjs appears to be ineffective

Why can't I color the chart area of my line graph using this code? options={{ maintainAspectRatio: false, title: { display: true, fontSize: 20 }, chartArea: { backgroundColor: ...

You must click the checkbox twice in order to mark it as checked

My code is experiencing an issue where only one clique is not accepted. To put a tick, it requires two clicks - once on the checkbox and then again on the "Save" button to see the tick appear after the page reloads. Javascript <script type="text/javas ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...

Tips for implementing conditional rendering with ReactJS

I have created a React component that generates a list of tasks. Currently, the code works fine with this.props.data, and if the data is empty, no tasks are displayed. My goal is to modify the code so that if the array is empty, a simple text message ...

"Dealing with Angular .map() function returning an empty array or displaying error messages

I'm encountering two issues while attempting to display data from my API call using the following code... API Call: getProducts(id: number) { return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe( switchMap(token => { ...

Problem with Bootstrap 5.3 navbar dropdown functionality not functioning as expected

I'm facing an issue with my code. I attempted to use both bootstrap 5.2 and 5.1, but neither seems to be working for me. I've tried opening it in both Chrome and Firefox, but the dropdown functionality is not functioning in either browser. Does a ...

Backend JS error found in Joomla 3.0 Component

Currently, I am working on developing a custom Joomla 3.0 component. To begin, I started by downloading the com_hello component sample from the official Joomla documentation. However, I've encountered an issue when trying to check the checkbox in the ...

Tutorial on efficiently parsing JSON data within a .NET Core class library

Currently, I am developing a versatile library utilizing the .NET Core class library project model and am in need of interacting with a REST service through JSON. Unfortunately, I am unable to utilize the JSON.NET Nuget package or "System.Runtime.Serializ ...

Tips for changing the size of a background image using JavaScript on the fly

I am a beginner in the world of programming and currently working on my very first mini-project - a word definition game. One of the challenges I am facing is related to an event listener on an input field, where I aim to change the background image every ...