What is the best way to organize this JSON Object based on price using Javascript?

Looking to organize a JSON object by sorting based on price from lowest to highest.

{
 "BEY": {
  "1": {
    "price": 2280,
    "airline": "QR",
  },
  "2": {
    "price": 2108,
    "airline": "UA",
  }
 },
 "BKK": {
  "1": {
    "price": 2956,
    "airline": "QR",
  },
  "2": {
    "price": 1718,
    "airline": "WS",
  }
 }
}

The goal is to re-arrange it so that the ticket price becomes the key. Here's an example:

{ 
  1718: {
   "airline" : "WS",
   "IATA_Code" : "BKK"
  },
  2108: {
   "airline" : "UA",
   "IATA_Code" : "BEY"
  },
  2280: {
   "airline" : "QR",
   "IATA_Code" : "BEY"
  },
  2956: {
   "airline" : "QR",
   "IATA_Code" : "BKK"
  }
}

Answer №1

There are three obstacles hindering your progress with this task.

  1. To achieve the desired outcome, you must navigate through both the main object and its sub-objects to extract the necessary key-value pairs.

  2. Additionally, organizing an object of objects is not feasible; using an array is a more suitable approach. I have converted your structure into an array of objects for better manipulation.

  3. Parsing your JSON accurately requires eliminating any extraneous commas following the "airline" values. Make sure to reference the correct JSON format provided in the text box before proceeding.

Hence, prior to converting your JSON data, it is crucial to utilize tools like JSLint or similar validators (e.g., JSHint) to confirm the validity of your JSON structure.

var inputJSON = JSON.parse(document.getElementById('json-data').value);
var outputJSON = JSON.stringify(convert(inputJSON), null, 4);

document.body.innerHTML = '<pre>' + outputJSON + '</pre>';

function convert(data) {
  var result = [];
  Object.keys(data).forEach(function(code) {
    Object.keys(data[code]).forEach(function(ticket) {
      var record = {
        'IATA_Code': code
      };
      Object.keys(data[code][ticket]).forEach(function(key) {
        record[key] = data[code][ticket][key];
      });
      result.push(record);
    });
  });
  return result.sort(function(a, b) {
    return a.price > b.price;
  });
};
<textarea id="json-data">
{
  "BEY": {
    "1": { "price": 2280, "airline": "QR" },
    "2": { "price": 2108, "airline": "UA" }
  },
  "BKK": {
    "1": { "price": 2956, "airline": "QR" },
    "2": { "price": 1718, "airline": "WS" }
  }
}
</textarea>

Upon executing the code snippet by clicking the button above, the JSON should be properly formatted as indicated below:

[{
  "IATA_Code": "BKK",
  "price": 1718,
  "airline": "WS"
}, {
  "IATA_Code": "BEY",
  "price": 2108,
  "airline": "UA"
}, {
  "IATA_Code": "BEY",
  "price": 2280,
  "airline": "QR"
}, {
  "IATA_Code": "BKK",
  "price": 2956,
  "airline": "QR"
}]

Answer №2

When dealing with multiple entries sharing the same price, it's important to consider your output data structure. Using the price as the key may pose a challenge, but you can overcome this by storing an array for each key to accommodate one or more entries at the same price.

To achieve this, you can utilize the following ES6 code snippet. The use of JSON.parse and JSON.stringify may not be necessary if the object is already available in JavaScript:

var obj = JSON.parse(`{
 "BEY": {
  "1": {
    "price": 2280,
    "airline": "QR"
  },
  "2": {
    "price": 2108,
    "airline": "UA"
  }
 },
 "BKK": {
  "1": {
    "price": 2956,
    "airline": "QR"
  },
  "2": {
    "price": 1718,
    "airline": "WS"
  }
 }
}`);

var result = Object.keys(obj).reduce( (acc, IATA_Code) =>
    Object.keys(obj[IATA_Code]).reduce( (acc, i) => {
        let price = obj[IATA_Code][i].price;
        acc[price] = (acc[price] || []).concat({
            airline: obj[IATA_Code][i].airline, 
            IATA_Code 
        });
        return acc;
    }, acc),
{});

console.log(JSON.stringify(result, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

The Blueimp File Uploader seems to be sending numerous submissions at once

I've been tasked with fixing an issue on our site that I didn't originally build. The previous developer who worked on this project is now occupied with another task, leaving me to figure out what's going wrong. We are utilizing the basic bl ...

Guide to dynamically using array.map based on a condition in React

I am encountering an issue with a modal screen that contains two dropdowns and a text input field. The problem arises when the second dropdown is set to “is empty”, as the text input field should then disappear, leaving just the two dropdown inputs on ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...

Tips for resolving the issue: 'Unhandled Promise Rejection: Error: Unable to resolve bare specifier "app.js" from http://localhost:3000/'

While delving into TypeScript, I have come across an error related to node modules. https://i.sstatic.net/IPx5A.png Upon clicking the anonymous function, it leads me to the following code snippet. https://i.sstatic.net/4U8dY.png <!DOCTYPE html> & ...

Present array information in a Vue.js interface

Here is the function of my controller $teams= ChallengeTeam::where('challenge_id', '=', $id) ->join('users AS leader', 'challenge_teams.team_leader_id', '=', 'leader.id') ...

Tips for fixing a missing page issue in an Angular 2 boilerplate

Recently, I started exploring Angular 2 and decided to clone the repository from this link: https://github.com/AngularClass/angular-starter. My goal was to add a new menu option called 'list'. After creating the necessary component and updating t ...

Developing customized tools for twitch broadcasters

While exploring the world of streaming, I stumbled upon various widgets like chatboxes and follower goals that piqued my interest. Now, I'm eager to create my own versions. One standout example is the streamlabs widgets. You can tweak the HTML/CSS/JS ...

What sets apart posting data through an HTML form submission from posting data through an Ajax request?

Recently, I've encountered an issue with my Post API. When calling it through AJAX, the user parameter is received but the StreamReader returns empty. [HttpPost] [Route("getUserBankList")] public IHttpActionResult getUserBankList(UserProfile ...

'Without the need to refresh the page, assign a JavaScript variable from JSP on the server side.'

I'm looking for a way to assign a JavaScript variable from JSP without triggering a full page reload. While my current code successfully sets the variable, it also causes the entire page to refresh as a side effect. Here's an example in the exam ...

javascript functionality may be affected in Internet Explorer and Firefox following the upgrade to jquery version 1.8.3

After upgrading to jquery 1.8.3 from jquery 1.7 (where everything was functioning properly in all browsers), I added a javascript plugin that specifically requires jquery 1.8.2 or 1.8.3 Unfortunately, the image resizing functionality of this javascript is ...

Is there a way for me to retrieve the name and extension of an attached file in an input field of type "text"?

Could you assist me with a task? I have a table and I would like to extract the name and extension of each file and insert it into an input field below each "file" type input. This information will then be saved into a MySQL database, allowing me to create ...

What is the process for inputting data into a Inertia component?

I have a simple component: <script setup> import {ref} from 'vue' const labels = [] </script> <template> <div v-for="(label, index) in labels" :key="index" v-html="label"></div> </t ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

Wrapping an array into a string in Laravel: a step-by-step guide

Is there a way to convert my return array into a string in Laravel? I would like it to look something like this: Laravel: $columnDefinitions = array(); $columnDefinition = new \stdClass(); $columnDefinition->label = "No"; $column ...

What is the best way to add a multiselect option in Django to display detailed information for each selected item

Experience the Description Image I am looking to develop a mini demonstration similar to the image provided. When I click on an item in the left column to select a country, I want the right column to dynamically display all the cities of the chosen countr ...

looking to get into deeper levels of JSON data with json.load

I have implemented Hufman's Honeywell Python code to extract data from the MyTotalConnectComfort website. The code can be accessed here. I made adjustments to the code for compatibility with version 2.7 and integrated Flask into the process. Upon cal ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

Exploring ways to iterate through an array of objects to extract specific values

Kindly read this information thoroughly before marking it as a duplicate. I currently possess an array of objects as shown below. const filterParams = [ { 'waterfront_type[]': 'Cove' }, { 'area[]': 'Applehead ...