New to JS, I come from Python world so need some help.
I am fetching some data from B.E. that looks something like:
{
"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" }]
},
}
}
I want to pick up Arrival/Departure data per airport and convert it into a list of dictionaries (Key /Value pairs) something that looks like this :
FlightData.Airports.BCN.Arrivals
[
{"0:00":[]},
{"1:00":["flight": BIO, "passengers": 10]},
{"2:00":["flight": VGU, "passengers": 20]},
{"3:00":["flight": MEX, "passengers": 30]},
]
Is there an easy way to do this. This is what I have tried so far:
let arrivalDict = Object.keys(arrivals).reduce(
(acc: any, k: any) => (
(acc[arrivals[k]] = [...(acc[arrivals[k]] || []), k]), acc
),
{}
);
Is it better to use Lodash?
2 Answers 2
Since arrivals is an array, you don't need to use Object.keys(). Just loop over the array values.
I've used a for loop to create a dictionary that has all the hours as keys. Then I use a forEach() loop to push each of the arrivals dictionaries onto the appropriate element.
let arrivals = [{ "flight": "BIO", "time": "1:00" , "passengers": 10}, { "flight": "VGU", "time" : "2.00","passengers": 20 }, {"flight": "MEX", "time": "3.00", "passengers": 30 } ];
// Fill in 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)
1 Comment
There are a few ways to accomplish this, if you don't mind starting with an array of times consider this approach:
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);
1 Comment
Explore related questions
See similar questions with these tags.
["flight": BIO, "passengers": 10]is not valid JavaScript.[]is for arrays, only objects havekey:valuepairs. Do you want an array of objects there?arrivals[k].timeas the key of the result.