Organize a JSON dataset

I am facing a challenge with a JSON structure that looks like this:

"hotel": [
{
    "id": 90091,
    "hotelGroup": "A1",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 1,
        "maximumQuantity": 6,
    },
    {
        "name":"Room2",
        "minimumQuantity": 7,
        "maximumQuantity": 12,
    }
]},
{
    "id": 90089,
    "hotelGroup": "A4",
    "hotelRoom": [
    {
        "name":"Room1",
        "minimumQuantity": 0,
        "maximumQuantity": 0,
    }]
}]

My aim is to restructure the JSON as shown below:

hotel = [{
    name: "Room1",
    RoomInfo: [{
        hotelGroup: "A1",
        Stops: [
            {"minimumQuantity": 1,"maximumQuantity": 6}
        ]}, 
        {
            hotelGroup: "A4",
            Stops: [
                {"minimumQuantity": 0,"maximumQuantity": 0}
            ]
        }
   ]}, 
   {
       name: "Room2",
       RoomInfo: [{
           Name: "A1",
           Stops: [
               {"minimumQuantity": 7,"maximumQuantity": 12}
           ]
      }]
 }]

If anyone has any advice or assistance on how to achieve this restructuring, it would be greatly appreciated. I am looking to group each hotel by its name and have its respective hotel group and stops nested accordingly.

Thank you in advance

Answer №1

Clearly transformed your JSON data into a standard array for better understanding.

const hotel = [{
    "id": 90091,
    "hotelGroup": "A1",
    "hotelRoom": [{
        "name": "Room1",
        "minimumQuantity": 1,
        "maximumQuantity": 6,
      },
      {
        "name": "Room2",
        "minimumQuantity": 7,
        "maximumQuantity": 12,
      }
    ]
  },
  {
    "id": 90089,
    "hotelGroup": "A4",
    "hotelRoom": [{
      "name": "Room1",
      "minimumQuantity": 0,
      "maximumQuantity": 0,
    }]
  }
];

const newHotels = hotel.map(obj => {
  const { hotelGroup, hotelRoom } = obj;
  const newObj = {};

  newObj['name'] = hotelRoom[0]['name'];

  newObj['RoomInfo'] = hotelRoom.map(({ minimumQuantity, maximumQuantity }) => {
    return {
      hotelGroup,
      Stops: [{
        minimumQuantity,
        maximumQuantity
      }]
    };
  });
  
  return newObj;
});

console.log(newHotels);

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

The json_decode function results in a null value

I save encrypted collections in a database, but when I attempt to decipher them, they come back as null. [{"id":13,"qty":"1"}] The arrays are encrypted using PHP, so I am unsure of what the issue could be. Appreciate any help. ...

Having trouble with Material UI ListItem and setting a custom key prop

While using Material UI for React, I encountered an issue when attempting to pass a key prop to a ListItem: A warning popped up stating that key is not a valid prop. Trying to access it results in undefined. If the same value is needed within the child ...

Issue with `styles` argument after updating from Material version 4 to 5: MUI

After recently upgrading from Material V4 to V5, I encountered the following error message: MUI: The `styles` argument provided is invalid. You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider ...

Accessing Firebase data using randomly generated keys

I need to extract the values associated with each key from my JSON file named cardInfo. "cardInfo" : { "-KF3fzOc3e68jRpCkLRb" : 6869098993309203, "-KF3g0fQUJHcexwAFzxz" : 6764366404306628, "-KF3hHOdj-siBxLMNgLa" : 4368998299921 ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

There seems to be an unidentified issue causing my carousel to malfunction

I'm currently experiencing an issue with the carousel on my Angular web application that is not functioning as expected. I am unable to determine the root cause of this problem -- here's my code <div id="section1" class="carousel slide" ...

What is the best way to retrieve the initial word from a JSON dictionary?

When working with JSON data and aiming to convert it into an Excel format, my goal is to arrange dictionary content in a tabular form in Excel. **Code** f = open(filename, 'r') #open json file data = json.loads(f.read()) #load js ...

The AngularJs script is encountering issues post-deployment, throwing an error [$injector:unpr]

I have been working on a web project and every time I try to publish it, I want to make sure it looks the same as it does on localhost. Recently, I added angularjs to handle currency display and when I deployed the project again, users are seeing {{currenc ...

What is the best location to include the sitemap.xml file within a NextJS project?

I recently completed building my NextJS website and utilized an online sitemap generator to create my sitemap.xml file. In the past, when working with ReactJS, I would place it in the public folder, or in the dist folder for projects using regular HTML, CS ...

Rearrange an irregular matrix using JavaScript

I have a matrix that can vary in width depending on the results received from the server. Here is an example: [undefined, undefined] [1, 2, 3, 4] [1, 2] [undefined, undefined, undefined] [1, 2, 3, 4, 5, 6] My goal is to transform it into this format: [u ...

Is there a way to launch an ajax request in a distinct frame?

So, I've come across this code snippet: <script language="javascript" type="text/javascript"> <!-- function loadContent(page) { var request = false; try { request = new XMLHttpRequest(); } catch (e) { try{ ...

Monitoring the content of a page with jQuery and adjusting the size as needed

Here is a code snippet: function adjustContainerHeight() { $('div#mainContainer').css({ 'min-height': $(document).height() - 104 // -104 compensates for a fixed header }).removeShadow().dropShadow({ 'blur&a ...

Comparing Xpath and CSS Selector in Scrapy: Exploring the Differences in Data Storage Methods

When it comes to extracting the title of an article, I have the choice between using xpath or css selectors. Although both methods will yield the same results, there is a key difference. XPath stores the data (json file) in square brackets ["Some Title"], ...

I am experiencing an issue where the Ajax/Javascript functionality is unresponsive on my homepage

I have been attempting to design a button using a simple Ajax / Javascript command. It seems to be functioning properly, but I am encountering an issue where it does not appear on the main page when inspecting with F12, causing some complications. Below i ...

Simple method to retrieve the ID of an input field within a form using jQuery selectors

I have a form with each input field having a unique id, and I have attached a jQuery 'input' event to the form. I want to retrieve the id of the field on which the user changes some value using a jQuery function. There seems to be something missi ...

"Enhance Your Data Display Experience with Angular ui-grid Tables, Easy Client-Side

I have a small project that I am transitioning from jquery to angularjs. Initially, I was using DataTables to display diagnostic data from my virtual machines. However, I am now exploring the use of ui-grid from angular-ui but faced some challenges with pa ...

The asp.net feature is presenting data that is not fully formed

While working with an Ajax request in JavaScript, I encountered an issue where the data being fetched is repeating in the last three fields. Upon validating the query in the database, it seems that the data retrieved by the Ajax call does not match what is ...

How to update an empty array in NodeJS using Mongoose

I am currently in the process of developing a NodeJS application that generates reports based on data from a Microsoft SQL database. All the relevant data for the application is stored in a MongoDB database using Mongoose. Within my Mongoose model, I have ...

Unlock the full potential of Ruby on Rails 5.0.2 with its ability to render multiple nested

I'm currently facing an issue while attempting to display multiple nested objects in json format. Below is the code snippet I am using: def getFullSale sale = Sale.find(params[:id]) render json: sale, include: [:discount_sale, :offer ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...