Combining various JSON objects by nesting them together

I'm in the process of creating an endpoint where I need to combine data from four different tables into one nested object. Each table record is retrieved in JSON format using sequelize - they include information on location, service, staff, and tenant. How can I merge these records into a single nested object? For example: The data obtained from sequelize for staff:

{
    "id": 2,
    "profession": "Dentist",
    "note": "Good Man",
    "holidays": "Saturday",
    "specialDays": null,
    "createdAt": "2023-01-27T14:23:52.000Z",
    "updatedAt": "2023-01-27T14:23:52.000Z"
}

All other data follows a similar format but I aim to merge them to create a combined output like this:

 {  
    staff:{
        "id": 2,
        "profession": "Dentist",
        "note": "Good Man",
        "holidays": "Saturday",
        "specialDays": null,
        "createdAt": "2023-01-27T14:23:52.000Z",
        "updatedAt": "2023-01-27T14:23:52.000Z",
    },
    location:{
        "id": 1,
        "name": "Branch 1",
        "address": "37 Automatic Handling",
        "description": "This is our main branch",
        "latitude": "564233",
        "longitude": "4441256",
        "visible": true,
        "createdAt": "2023-01-27T14:05:37.000Z",
        "updatedAt": "2023-01-27T14:05:37.000Z",
    } 
}

Answer №1

If you want to create an object, simply follow these steps:

// (within an async function)

const location = await // code using Sequelize to retrieve information
const service = await // code using Sequelize to retrieve information
const staff = await // code using Sequelize to retrieve information
const tenant = await // code using Sequelize to retrieve information

return res.json({
  location,
  service,
  staff,
  Tenant: tenant, // delete "Tenant:" if it was a mistake or not important
});

Answer №2

Yes, this code snippet seems like it should function properly!

const staff = {
    "id": 2,
    "profession": "Dentist",
    "note": "Good Man",
    "holidays": "Saturday",
    "specialDays": null,
    "createdAt": "2023-01-27T14:23:52.000Z",
    "updatedAt": "2023-01-27T14:23:52.000Z",
};

const location1 = {
    "id": 1,
    "name": "Branch 1",
    "address": "37 Automatic Handling",
    "description": "This is our main branch",
    "latitude": "564233",
    "longtitude": "4441256",
    "visible": true,
    "createdAt": "2023-01-27T14:05:37.000Z",
    "updatedAt": "2023-01-27T14:05:37.000Z",
};

const mergedObject = { staff, location1 };
console.log(mergedObject);

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

Purpose of triggering another function during an ajax request

I have encountered an issue while working on a project. There is a page with an input field called balance within a div named balanceDiv. This field should not be visible to the admin, so I used ng-show to hide/show the div based on the user's login I ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

JavaScript method not properly sorting the last nested array

I am having trouble with sorting the last nested array using arr[i].sort(). Despite trying various methods such as FOR and WHILE loops along with different operators, I still cannot achieve the desired result. Can someone help me identify what I am doing w ...

Image not showing up when using drawImage() from canvas rendering context 2D

Need help with drawImage() method in JavaScript <head> </head> <body> <script type = "text/javascript"> var body, canvas, img, cxt; body = document.getElementsByTagName("body" ...

The ASP.NET MVC controller falling behind due to a delay in conversion process

Currently, I am transferring an array of DTOs from a local application to ASP.NET MVC. This process is being tested on my personal machine. The local application, being a Web Forms system, sends the data through a service without utilizing JsonResult. Al ...

What separates the various methods of initiating a node+express application?

As I delve into the world of Node and Express, I've come across multiple methods for initializing an application. Specifically, I've been working on a project called "nodetest" and here are the initial steps I took: Firstly, I installed express ...

Track the cursor's movement

Looking to add an animation effect to my website. I want the navbar to follow the cursor within a limited space when hovered over. Check out this example for reference: . Here's the code I have so far, but it's not quite achieving the desired res ...

Understanding the process of reading an ordereddict from a json file

Looking at this json data, d = {"id": 1, "company_car": 1, "manufacture_stage": OrderedDict([("id", 4), ("company", OrderedDict([("id", 1), ("name", "BMW"), ("icon", "http://test.com/ta/")]))]), "manufacture_car_stage_status": "Scheduled", "start_datetime ...

Tips for determining the height of the entire webpage using jQuery

I attempted the following code: $(window).height(); $("#content").height(); However, it did not provide an accurate value. ...

Is there a way to send multiple actions to Node.js via a dropdown list using POST method?

I have encountered an issue where I am trying to include multiple actions in a single form within a dropdown list. However, I am only able to POST one action at a time. admin.html <form action="/start" method="post" id="tableForm"> <select id= ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...

Tips for performing a conditional recursive merge

I am looking to perform a recursive merge conditionally. This means that if a key exists in the second object, I want it to override values in the first object. For instance, consider the following scenario: $ echo '{"a":"value"}{"bar": {"a":"overrid ...

"Learn the technique of adding a new data attribute before every element in a step-by-step

I am currently working with the following HTML code: <div id="elem"> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="bbb"></div> < ...

Using HTML5 Canvas with Firefox 4: How to Retrieve Click Coordinates

Lately, I've been diving into creating HTML5 Video and Canvas demos. Initially, my focus was on optimizing them for Chrome, but now I'm shifting my attention to Firefox and Safari as well. One particular demo I'm currently working on involv ...

How to extract data from Google Sheets using NODEJS?

When utilizing the REST API to extract data from a cell range in Google Sheets, the response returned is as follows: { "range": "RECORD!A2:J2", "majorDimension": "ROWS", "values": [ [ "07/11/2016", "21:20:10", "3", "MAIN" ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

What is the best way to utilize jq to arrange the contents of this JSON file based on the seconds value?

Here is a snippet of json data: { "results": [ { "request": { "metric": "CLOUDFREE_TIME_PERCENT", "path": { "fromPoint" ...

Perform two jQuery AJAX post requests using the identical object

My goal is to achieve the following: <form> <input type="button" class="btn btn-warning" id="follow" value="Follow"> </form> <script type="text/javascript'> $('#follow').click(function(){ $.ajax({ ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...