What is the process for changing a JSON string into a JavaScript array?

I've searched extensively but still haven't found a suitable solution.

Currently, I have a JSON string that is being retrieved from the server. My goal is to convert this string into a JavaScript array in order to organize the data by "hotel_name," 'minPrice,' and 'hotel_star.'

Below is the JSON string:

   {
   "00001065": {
      "hotel_id": "00001065",
      "hotel_name": "The Infantry Hotel",
      "hotel_star": "3",
      "image": "",
      "location": "Infantry Road",
      "minPrice": "2,497",
      "RoomTypes": [
         {
            "RoomTypeName": "Deluxe King / Twin Double",
            "AvailableQuantity": "4",
            "RatePlanInclusions": "Complimentary Wi-Fi Internet",
            "price": "2,497"
         },
         {
            "RoomTypeName": "Superior Double",
            "AvailableQuantity": "2",
            "RatePlanInclusions": "Breakfast",
            "price": "3,496"
         }
      ]
   },
   "00001080": {
      "hotel_id": "00001080",
      "hotel_name": "Hotel Ramanashree",
      "hotel_star": "3",
      "image": "",
      "location": "Richmond Road",
      "minPrice": "3,879",
      "RoomTypes": [
         {
            "RoomTypeName": "Executive Room",
            "AvailableQuantity": "25",
            "RatePlanInclusions": "Breakfast",
            "price": "3,879"
         },
         {
            "RoomTypeName": "Club Room",
            "AvailableQuantity": "25",
            "RatePlanInclusions": "Breakfast",
            "price": "4,604"
         }
      ]
   },
   "00003757": {
      "hotel_id": "00003757",
      "hotel_name": "The Paul ",
      "hotel_star": "5",
      "image": "",
      "location": "Domlur Layout",
      "minPrice": "6,216",
      "RoomTypes": [
         {
            "RoomTypeName": "Executive Suite - Two  Bedrooms Suite",
            "AvailableQuantity": "4",
            "RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
            "price": "8,942"
         },
         {
            "RoomTypeName": "Premier Suite - Two  Bedrooms Suite",
            "AvailableQuantity": "2",
            "RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
            "price": "10,718"
         },
         {
            "RoomTypeName": "Studio Suite - One  Bedroom Suite",
            "AvailableQuantity": "4",
            "RatePlanInclusions": "Complimentary Wi-Fi Internet, Breakfast",
            "price": "6,216"
         }
      ]
   }
}

Answer №1

If you're new to JavaScript, starting with a JSON tutorial might be beneficial before diving into more complex tasks. An excellent resource to begin with is MDN.

One handy function in JavaScript is the ability to parse JSON data and convert it into an array.

// Function to convert an object into an array
function objectToArray(obj) {
    var array = [];
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            array.push(obj[prop]);
        }
    }
    return array;
}

var obj = JSON.parse(json_string);
var arr = objectToArray(obj);

To manipulate the array further, you can explore sorting it using the sort() method and create your own compareFunction.

Answer №2

Sorting a JSON object does not require converting it into an array first. You can simply sort the JSON object itself.

function sortResults(prop, asc) {
    arr = arr.sort(function(a, b) {
        if (asc) return (a[prop] > b[prop]);
        else return (b[prop] > a[prop]);
    });
}

I have implemented a demonstration with your JSON data where you can click on the headers to see the sorting in action: http://jsfiddle.net/VAKrE/922/

Answer №3

This is a possible way to achieve the desired result:

let data = JSON.parse("...");

let asArray = Object.keys(data).map(function(key) { return data[key] });

asArray.sort(function(x, y) {
    if(x.hotel_name > y.hotel_name) return 1;
    if(x.hotel_name < y.hotel_name) return -1;
    return 0;
});

Answer №4

let obj = JSON.parse(dataFromServer);

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

Unable to alter the state through the URL bar using ui-router

I am facing an issue where I get redirected to the home state whenever I try to directly access a URL like mysite.com/#!/about. My menu with ui-sref links is functioning correctly, but when it comes to nested states, I encounter problems switching betwee ...

Is it possible to have the front-facing photo in expo-camera stay mirrored?

Currently, I am utilizing the expo-camera library to capture a selfie image. Despite the preview being mirrored, the final saved image reverts to its normal orientation. Is there any way to avoid this behavior so that the image remains mirrored? Alternativ ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

jQuery file uploader only transmitting a single chunk

Currently, I am integrating the jQuery file uploader into my Django application. I am encountering an issue where Django is only receiving one chunk of my large file. Initially, I suspected a problem with my UploadFileHandler; however, upon logging the ch ...

Enhancing User Experience with Real-Time Control Updates using ASP.Net and Bootstrap

I am struggling to figure out how to update bootstrap controls with ASP.Net. Here is the code I am working with: @{ Layout = null; } <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width ...

Transforming an array of JavaScript objects into arrays of key-value pairs based on a specific property with ES6 syntax

Consider an array of objects like this: myArray = [ {name: 'First', parent: 1, delta: 2}, {name: 'Second', parent: 1, delta: 1}, {name: 'Third', parent: 2, delta: 1} ]; The goal is to transform this array into an objec ...

Ways to update a single column in an HTML table when there is a change

I'm stuck trying to find a more efficient method for updating a column in an html table without having to reload the entire table. The table consists of player stats, all pulled from my MYSQL database and displayed in the table except for the last col ...

Why am I getting a null value for my Array when I should be expecting an Object instead?

I have been attempting to create an Array that contains objects for a project, but I keep encountering an error message stating: "this.allgmArray is undefined". However, it is not actually undefined: allgmArray: DialogBook[]; [...] load(){ for(var i ...

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...

Looping over the values of two arrays in a Bash script using a for loop

In the file /etc/trueuserdomains, each line contains a username paired with its associated domain. My goal is to create symbolic links using the command ln -s /home/$user /var/www/vhosts/$domain for each pair listed. I have successfully defined two arrays ...

Learn the steps for submitting and interpreting information in Node Express

I am attempting to send this JSON data to a node express endpoint { "data": [ [ "Audit Territory", "LA Antelope Valley", "LA Central", "LA East San Gabriel", "LA San Fernando Valley", "LA West", ...

Updating multiple array elements in MongoDB

Recently, I came across a document that has the following structure: { codeId: 1, generatedCodes: [ { name: 'Code 1', status: 'In Progress' }, { name: 'Code 2', status: 'In Progres ...

Learn how to transform JSON data into a model class in Dart, similar to the format shown in the image provided. This tutorial will demonstrate

quicktype.io app is encountering issues with converting, specifically skipping digit class names class ScoreCardModel { bool? status; String? msg; Data? data; ScoreCardModel({this.status, this.msg, this.data}); ScoreCardModel.fromJson(Map<St ...

What is the best method to assign a property to a model within AngularJS by utilizing an attribute parameter?

I am in the process of creating a custom directive in AngularJS for a UI slider that can be used multiple times. Each slider should be able to bind to a specific property. My idea was to use an attribute called "property" which would automatically update w ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Adding an object to an array in Postgres with TypeORM

I am currently facing an issue with the column in my Postgres database that has a data type of json. The code snippet for this scenario is as follows: @Column({ type: 'jsonb', nullable: false, default: [] }) us ...

Error encountered when trying to run the pbGetDevices() function on a Windows 11 computer, specifically related to RPushbullet

Struggling to get the RPushbullet package up and running on my Windows 11 system with R 4.1.1. I've set up the necessary json file in the $HOME directory, but when I attempt to execute the command fromJSON(pbGetDevices())$devices[,c("iden", ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Applying jQuery .animate() to elements without specifying position: absolute

My goal is to create a website where clicking on an image triggers a dropdown menu. The jQuery method I'm using is as follows: function main() { $('#arrow').click(function() { $('.hidden').animate({ top: &a ...