Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance.

Currently, I am retrieving data from the back end that has the following structure:

{
  "Airports": {
    "BCN": {
      "Arrivals": [{ "flight": "BIO", "time": "1:00" , "passengers": 10}, { "flight": "VGU", "time" : "2.00","passengers": 20 }, {"flight": "MEX", "time": "3.00", "passengers": 30 } ],
      "Departures": [{ "flight": "BIO", "time": "1:00" }, { "flight": "VGU", "time" : "2.00" }, {"flight": "MEX", "time": "3.00" }]
    },
 
  }
}

My goal is to extract Arrival/Departure data for each airport and transform it into a list of dictionaries containing key-value pairs as shown below:

FlightData.Airports.BCN.Arrivals

[
{"0:00":[]},
{"1:00":["flight": BIO, "passengers": 10]},
{"2:00":["flight": VGU, "passengers": 20]},
{"3:00":["flight": MEX, "passengers": 30]},
]

I have tried the following approach so far:

let arrivalDict = Object.keys(arrivals).reduce(
    (acc: any, k: any) => (
      (acc[arrivals[k]] = [...(acc[arrivals[k]] || []), k]), acc
    ),
    {}
  );

Should I consider using Lodash for this task?

Answer №1

Instead of using Object.keys(), you can directly loop over the array values since arrivals is an array.

I opted for a for loop to generate a dictionary with hours as keys. Then, I utilized a forEach() loop to append each arrivals dictionary to the corresponding element.

let arrivals = [{ "flight": "BIO", "time": "1:00" , "passengers": 10}, { "flight": "VGU", "time" : "2.00","passengers": 20 }, {"flight": "MEX", "time": "3.00", "passengers": 30 } ];

// Populate all hours from 00:00 to 23:00
let arrivals_obj = {};
for (let hour = 0; hour < 24; hour++) {
  arrivals_obj[`${hour}:00`] = [];
}

Object.values(arrivals).forEach(arrival =>
  arrivals_obj[arrival.time.replace('.', ':')].push(arrival)
);

console.log(arrivals_obj)

Answer №2

If you're open to working with an array of times, there are several methods you can use to achieve this goal. One approach is to start by considering the following:

const data = {
  "Airports": {
    "BCN": {
      "Arrivals": [
        { "flight": "BIO", "time": "1:00" , "passengers": 10}, 
        { "flight": "VGU", "time" : "2:00","passengers": 20 }, 
        {"flight": "MEX", "time": "3:00", "passengers": 30 } 
      ],
      "Departures": [
        { "flight": "BIO", "time": "1:00" }, 
        { "flight": "VGU", "time" : "2:00" }, 
        { "flight": "MEX", "time": "3:00" }
      ]
    }
  }
};

const times = ["0:00", "1:00", "2:00", "3:00"];

const result = Object.fromEntries(
  times.map(t => [t, data.Airports.BCN.Arrivals.filter(arr => arr.time === t)])
);

console.log(result);

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

After an AJAX request is completed, the event.keyCode is not returning the key codes for the up and

I have a function that uses AJAX to autocomplete a text field. The results are added to a specific div element. I am trying to implement the functionality where users can navigate through the results using the up and down arrow keys. However, I am encoun ...

Using an AngularJS ng-repeat alias expression with multiple filters

As stated in the Angular ngRepeat documentation, the alias expression can only be used at the end of the ngRepeat: It's important to note that `as [variable name]` is not an operator, but rather a part of the ngRepeat micro-syntax and must be place ...

Looking to extract a specific field using Angular JS?

The JSON data I need is fetched from the link provided below: http://maps.googleapis.com/maps/api/geocode/json?address=SFO When retrieving the JSON, only the parameter example ?adress=sfo should be used. This will result in fetching all values associated ...

Modify the text of a button using JavaScript without referencing a specific div class

THE ISSUE I'm facing a challenge in changing the text of a button on my website. The <div> I need to target doesn't have a specific class, making it difficult for me to make this edit. While I have some basic understanding of JavaScript, ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages │ └───Work │ │ index.vue │ │ [Work].vue Template <templat ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Ways to retrieve a specific Array[property] within an object?

I am struggling to access a specific property within an array of objects. My goal is to extract the "name" elements from the app catalog array, combine them with the names from the custom array apps.name, and assign the result to a new property in the ques ...

An error was encountered in compiler.js at line 1021, stating that an unexpected value 'UserService' was imported by the module 'UserModule'. It is recommended to add a @NgModule annotation to resolve this issue

As a PHP programmer new to Angular, I am facing an issue while trying to retrieve user properties from a Laravel API. When attempting this, I encountered the following error: compiler.js:1021 Uncaught Error: Unexpected value 'UserService' importe ...

Generate text in a random spot effortlessly

After doing some research on various development platforms, I stumbled upon this JSFiddle that seems to have a solution for my requirements. The only thing missing is the ability to input a specific word (without user input) and automate the process at fix ...

Combining the Powers of Angular JS and Symfony2

Currently working on a project involving Symfony2 and in need of some advice. Considering a hybrid application approach in two ways: a) Using a traditional form with CSRF Token for the Login Page handled by Symfony2, and b) Inner pages (potentially module ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Excessive iterations occurring in JavaScript for loop while traversing an array

After addressing the issues raised in my previous inquiry, I have made significant progress on my project and it is now functioning almost exactly as intended. The main purpose of this website is to iterate through the World Of Tanks API to generate cards ...

Activate function on Selected DIV

Within this div, I have set the tabindex attribute to '-1' so that it can be focused on mouse click. <div tabindex='-1'></div> .div:focus{//some style} My goal is to use jQuery to perform an action when a user clicks on th ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

In Typescript, convert an object into a different type while maintaining its keys in the resulting type

Imagine you have a code snippet like this type ResourceDecorator = (input: UserResourceDefinition) => DecoratedResourceDefinition const decorate: ResourceDecorator = ... const resources = decorate({ Book1: { resourceName: 'my-book', ...

Unpacking Constructor with visible arguments

In my constructor, I utilize destructuring to simplify the parameters needed to create an object with default values. export class PageConfig { constructor({ isSliding = false }: { isSliding?: boolean; getList: (pagingInfo: PagingInfo) =&g ...