How to compare object properties between different objects in different arrays - javascript

I am getting data from 2 APIs, one returns the data from 18 different airports, and one returns the flighst from one airport to another (this API needs to be fed with the id of the departure airport and the arrival airport)
The API that returns the flights is like this one here:
{
"data": [
{
"id": 64,
"airlineId": 8,
"departureAirportId": 5,
"arrivalAirportId": 2,
"price": 205.75
},
{
"id": 42,
"airlineId": 7,
"departureAirportId": 2,
"arrivalAirportId": 17,
"price": 1324.42
}
]
}
While The API that returns the airports is this one:
{
"data": [
{
"id": 1,
"codeIata": "PSA",
"latitude": 43.6931,
"longitude": 10.3789
},
{
"id": 2,
"codeIata": "BLQ",
"latitude": 44.5357,
"longitude": 11.2736
},
{
"id": 3,
"codeIata": "BGY",
"latitude": 45.6702,
"longitude": 9.6715
},
{
"id": 4,
"codeIata": "MXP",
"latitude": 45.6289,
"longitude": 8.7183
},
{
"id": 5,
"codeIata": "TRN",
"latitude": 45.1934,
"longitude": 7.6158
},
{
"id": 6,
"codeIata": "VCE",
"latitude": 45.5046,
"longitude": 12.3444
},
{
"id": 7,
"codeIata": "FCO",
"latitude": 41.8025,
"longitude": 12.213
},
{
"id": 8,
"codeIata": "PSR",
"latitude": 42.4261,
"longitude": 14.1793
},
{
"id": 9,
"codeIata": "NAP",
"latitude": 40.8819,
"longitude": 14.2731
},
{
"id": 10,
"codeIata": "BRI",
"latitude": 41.1375,
"longitude": 16.763
},
{
"id": 11,
"codeIata": "BDS",
"latitude": 40.6551,
"longitude": 17.936
},
{
"id": 12,
"codeIata": "SUF",
"latitude": 38.9057,
"longitude": 16.2402
},
{
"id": 13,
"codeIata": "CTA",
"latitude": 37.4667,
"longitude": 15.0639
},
{
"id": 14,
"codeIata": "PMO",
"latitude": 38.1813,
"longitude": 13.0994
},
{
"id": 15,
"codeIata": "NRT",
"latitude": 35.7653,
"longitude": 140.386
},
{
"id": 16,
"codeIata": "KLX",
"latitude": 37.0683,
"longitude": 22.0256
},
{
"id": 17,
"codeIata": "ALA",
"latitude": 43.3553,
"longitude": 77.0447
},
{
"id": 18,
"codeIata": "PEK",
"latitude": 40.0725,
"longitude": 116.5975
}
]
}
I need to take the "departureAirportId" and the "arrivalAirportId" from the flights API, check them against the airport API and fetch the name of the airport according the provided id.
I tried in many ways but each time I ended up digging a huge rabbit hole and decided just to restart all over for I do not know how many times now.
Any suggestion how I could do this?

This should solve your problem:
let flights = {
"data": [{
"id": 64,
"airlineId": 8,
"departureAirportId": 5,
"arrivalAirportId": 2,
"price": 205.75
},
{
"id": 42,
"airlineId": 7,
"departureAirportId": 2,
"arrivalAirportId": 17,
"price": 1324.42
}
]
};
let airports = {
"data": [{
"id": 1,
"codeIata": "PSA",
"latitude": 43.6931,
"longitude": 10.3789
},
{
"id": 2,
"codeIata": "BLQ",
"latitude": 44.5357,
"longitude": 11.2736
},
{
"id": 3,
"codeIata": "BGY",
"latitude": 45.6702,
"longitude": 9.6715
},
{
"id": 4,
"codeIata": "MXP",
"latitude": 45.6289,
"longitude": 8.7183
},
{
"id": 5,
"codeIata": "TRN",
"latitude": 45.1934,
"longitude": 7.6158
},
{
"id": 6,
"codeIata": "VCE",
"latitude": 45.5046,
"longitude": 12.3444
},
{
"id": 7,
"codeIata": "FCO",
"latitude": 41.8025,
"longitude": 12.213
},
{
"id": 8,
"codeIata": "PSR",
"latitude": 42.4261,
"longitude": 14.1793
},
{
"id": 9,
"codeIata": "NAP",
"latitude": 40.8819,
"longitude": 14.2731
},
{
"id": 10,
"codeIata": "BRI",
"latitude": 41.1375,
"longitude": 16.763
},
{
"id": 11,
"codeIata": "BDS",
"latitude": 40.6551,
"longitude": 17.936
},
{
"id": 12,
"codeIata": "SUF",
"latitude": 38.9057,
"longitude": 16.2402
},
{
"id": 13,
"codeIata": "CTA",
"latitude": 37.4667,
"longitude": 15.0639
},
{
"id": 14,
"codeIata": "PMO",
"latitude": 38.1813,
"longitude": 13.0994
},
{
"id": 15,
"codeIata": "NRT",
"latitude": 35.7653,
"longitude": 140.386
},
{
"id": 16,
"codeIata": "KLX",
"latitude": 37.0683,
"longitude": 22.0256
},
{
"id": 17,
"codeIata": "ALA",
"latitude": 43.3553,
"longitude": 77.0447
},
{
"id": 18,
"codeIata": "PEK",
"latitude": 40.0725,
"longitude": 116.5975
}
]
};
const findAirportByID = (airportID) => {
return airports.data.filter(item => item.id == airportID);
}
flights.data.forEach(flight => {
let departureAirport = findAirportByID(flight.departureAirportId);
if(departureAirport[0])
flight.deparureAirportCode = departureAirport[0].codeIata;
let arrivalAirport = findAirportByID(flight.arrivalAirportId);
if(arrivalAirport[0])
flight.arrivalAirportCode = arrivalAirport[0].codeIata;
});
console.log(flights);

Related

Javascript get users location(country, lang, timezone)

I would like to collect all info which can be fetched from user without ask any permissions.
I don't want to use any of non-free ip info services and Geolocation
What I have now:
timeZoneOffset = new Date().getTimezoneOffset();
userLang = navigator.language || navigator.userLanguage;
But I want more info about users location.
Solution 1: The HTML Geolocation API is used to get the geographical position of a user.
But it asked user for permission.
Solution 2: Free IP Location API
Check this: https://ipdata.co/
$.getJSON('https://geolocation-db.com/json/')
.done (function(location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
});
Solution 3: PAID IP based API
There is no other solution for this.
The other answers mention paid services (ipdata) or free services without the data you need - timezone, etc - (geolocation-db.com)
I believe Abstract has a free plan for their IP geolocation API that includes timezone data among others: https://www.abstractapi.com/ip-geolocation-api
$.getJSON("https://ipgeolocation.abstractapi.com/v1/?api_key=****************", function(data) {
console.log(data.ip_address);
console.log(data.country);
console.log(data.timezone);
})
You can use BigDataCloud's IP Geolocation API to get maximum data from the IP address of your website visitor.
It provides 10K queries per month for free.
https://www.bigdatacloud.com/ip-geolocation-apis/ip-address-geolocation-api
Output data:
{
"ip": "73.231.131.73",
"localityLanguageRequested": "en",
"isReachableGlobally": true,
"country": {
"isoAlpha2": "US",
"isoAlpha3": "USA",
"m49Code": 840,
"name": "United States of America",
"isoName": "United States of America (the)",
"isoNameFull": "the United States of America",
"isoAdminLanguages": [
{
"isoAlpha3": "eng",
"isoAlpha2": "en",
"isoName": "English",
"nativeName": "English"
}
],
"unRegion": "Americas/Northern America",
"currency": {
"numericCode": 840,
"code": "USD",
"name": "US Dollar",
"minorUnits": 2
},
"wbRegion": {
"id": "NAC",
"iso2Code": "XU",
"value": "North America"
},
"wbIncomeLevel": {
"id": "HIC",
"iso2Code": "XD",
"value": "High income"
},
"callingCode": "1",
"countryFlagEmoji": "🇺🇸"
},
"location": {
"continent": "North America",
"continentCode": "NA",
"isoPrincipalSubdivision": "California",
"isoPrincipalSubdivisionCode": "US-CA",
"city": "Milpitas",
"localityName": "Milpitas",
"postcode": "95035",
"latitude": 37.45,
"longitude": -121.92,
"plusCode": "849WF32J+22",
"timeZone": {
"ianaTimeId": "America/Los_Angeles",
"displayName": "(UTC-08:00) Pacific Standard Time",
"effectiveTimeZoneFull": "Pacific Standard Time",
"effectiveTimeZoneShort": "PST",
"utcOffsetSeconds": -28800,
"utcOffset": "-08",
"isDaylightSavingTime": false,
"localTime": "2021-02-28T17:11:59.1873233"
},
"localityInfo": {
"administrative": [
{
"order": 2,
"adminLevel": 2,
"name": "United States of America",
"description": "country in North America",
"isoName": "United States of America (the)",
"isoCode": "US",
"wikidataId": "Q30",
"geonameId": 6252001
},
{
"order": 4,
"adminLevel": 4,
"name": "California",
"description": "state of the United States of America",
"isoName": "California",
"isoCode": "US-CA",
"wikidataId": "Q99",
"geonameId": 5332921
},
{
"order": 6,
"adminLevel": 6,
"name": "Santa Clara County",
"description": "county in California, United States",
"wikidataId": "Q110739",
"geonameId": 5393021
},
{
"order": 8,
"adminLevel": 8,
"name": "Milpitas",
"description": "city in Santa Clara County, California",
"wikidataId": "Q927510",
"geonameId": 5373327
}
],
"informative": [
{
"order": 1,
"name": "North America",
"description": "continent on the Earth's northwestern quadrant",
"isoCode": "NA",
"wikidataId": "Q49",
"geonameId": 6255149
},
{
"order": 3,
"name": "contiguous United States",
"description": "48 states of the United States apart from Alaska and Hawaii",
"wikidataId": "Q578170"
},
{
"order": 5,
"name": "Pacific Coast Ranges",
"description": "A series of mountain ranges along the Pacific coast of North America",
"wikidataId": "Q660304"
},
{
"order": 7,
"name": "95035",
"description": "postal code"
}
]
}
},
"lastUpdated": "2021-02-28T23:39:21.8284029Z",
"network": {
"registry": "ARIN",
"registryStatus": "assigned",
"registeredCountry": "US",
"registeredCountryName": "United States of America",
"organisation": "Comcast Cable Communications, LLC",
"isReachableGlobally": true,
"isBogon": false,
"bgpPrefix": "73.231.0.0/16",
"bgpPrefixNetworkAddress": "73.231.0.0",
"bgpPrefixLastAddress": "73.231.255.255",
"totalAddresses": 65536,
"carriers": [
{
"asn": "AS33651",
"asnNumeric": 33651,
"organisation": "Comcast Cable Communications LLC",
"name": "CMCS",
"registry": "ARIN",
"registeredCountry": "US",
"registeredCountryName": "United States of America",
"registrationDate": "2005-02-17",
"registrationLastChange": "2021-01-26",
"totalIpv4Addresses": 3147776,
"totalIpv4Prefixes": 217,
"totalIpv4BogonPrefixes": 0,
"rank": 152,
"rankText": "#152 out of 70,908"
}
],
"viaCarriers": [
{
"asn": "AS7922",
"asnNumeric": 7922,
"organisation": "Comcast Cable Communications LLC",
"registeredCountry": "US",
"registeredCountryName": "United States of America",
"totalIpv4Addresses": 24911902,
"rank": 15
}
]
},
"confidence": "high",
"confidenceArea": [
{
"latitude": 37.41,
"longitude": -122.244804
},
{
"latitude": 37.42,
"longitude": -122.244804
},
{
"latitude": 37.483982,
"longitude": -122.23432
},
{
"latitude": 37.513985,
"longitude": -122.22432
},
{
"latitude": 37.557896,
"longitude": -122.20398
},
{
"latitude": 37.598026,
"longitude": -122.17369
},
{
"latitude": 37.632973,
"longitude": -122.134514
},
{
"latitude": 37.66151,
"longitude": -122.08782
},
{
"latitude": 37.68264,
"longitude": -122.03526
},
{
"latitude": 37.69562,
"longitude": -121.97865
},
{
"latitude": 37.7,
"longitude": -121.92
},
{
"latitude": 37.7,
"longitude": -121.89
},
{
"latitude": 37.6962,
"longitude": -121.83531
},
{
"latitude": 37.684914,
"longitude": -121.782295
},
{
"latitude": 37.666485,
"longitude": -121.732544
},
{
"latitude": 37.64147,
"longitude": -121.687584
},
{
"latitude": 37.62147,
"longitude": -121.657585
},
{
"latitude": 37.582153,
"longitude": -121.610214
},
{
"latitude": 37.535625,
"longitude": -121.57468
},
{
"latitude": 37.484097,
"longitude": -121.55265
},
{
"latitude": 37.43,
"longitude": -121.5452
},
{
"latitude": 37.42,
"longitude": -121.5452
},
{
"latitude": 37.364517,
"longitude": -121.55305
},
{
"latitude": 37.311806,
"longitude": -121.5762
},
{
"latitude": 37.26449,
"longitude": -121.61351
},
{
"latitude": 37.25449,
"longitude": -121.62351
},
{
"latitude": 37.22382,
"longitude": -121.65991
},
{
"latitude": 37.19844,
"longitude": -121.70228
},
{
"latitude": 37.188442,
"longitude": -121.722275
},
{
"latitude": 37.16475,
"longitude": -121.78348
},
{
"latitude": 37.15206,
"longitude": -121.84966
},
{
"latitude": 37.150974,
"longitude": -121.91773
},
{
"latitude": 37.161533,
"longitude": -121.98451
},
{
"latitude": 37.17153,
"longitude": -122.02451
},
{
"latitude": 37.17153,
"longitude": -122.02451
},
{
"latitude": 37.19254,
"longitude": -122.085304
},
{
"latitude": 37.223186,
"longitude": -122.1392
},
{
"latitude": 37.262123,
"longitude": -122.18382
},
{
"latitude": 37.307613,
"longitude": -122.21719
},
{
"latitude": 37.357647,
"longitude": -122.23782
},
{
"latitude": 37.41,
"longitude": -122.244804
}
],
"securityThreat": "unknown",
"hazardReport": {
"isKnownAsTorServer": false,
"isKnownAsVpn": false,
"isKnownAsProxy": false,
"isSpamhausDrop": false,
"isSpamhausEdrop": false,
"isSpamhausAsnDrop": false,
"isBlacklistedUceprotect": false,
"isBlacklistedBlocklistDe": false,
"isKnownAsMailServer": false,
"isKnownAsPublicRouter": false,
"isBogon": false,
"isUnreachable": false,
"hostingLikelihood": 0,
"isHostingAsn": false,
"isCellular": false
}
}

How to rectify syntax error that of a NodeJS express server code?

This code below is throwing a syntax error that I cannot seem to rectify.
The error specifically is as follows:
node staticapi.js
/Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123
res.status(200).send(“Api is running”)
SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1152:16)
at Module._compile (internal/modules/cjs/loader.js:1200:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1257:10)
at Module.load (internal/modules/cjs/loader.js:1085:32)
at Function.Module._load (internal/modules/cjs/loader.js:950:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
Also i know how to create a route to accept the parameter for city in general but how do i create a route which filters my json result based on a specific city. Not just by cities in general but instead filter json by restaurants in Delhi per se.
const app = express();
const port = 8700;
var location = [
{
"_id": 1,
"name": "Pitampura, New Delhi",
"city_name": "Delhi",
"city": 1,
"area": 11,
"country_name": "India",
},
{
"_id": 2,
"name": "Ashok Vihar Phase 2",
"city_name": "Delhi",
"city": 1,
"area": 12,
"country_name": "India",
},
{
"_id": 3,
"name": "Laxmi Nagar",
"city_name": "Delhi",
"city": 1,
"area": 13,
"country_name": "India",
},
{
"_id": 4,
"name": "Lajpat Nagar 2",
"city_name": "Delhi",
"city": 1,
"area": 14,
"country_name": "India",
},
{
"_id": 5,
"name": "Borivali West",
"city_name": "Mumbai",
"city": 2,
"area": 21,
"country_name": "India",
},
{
"_id": 6,
"name": "Mira Road",
"city_name": "Mumbai",
"city": 2,
"area": 22,
"country_name": "India",
},
{
"_id": 7,
"name": "Sion",
"city_name": "Mumbai",
"city": 2,
"area": 23,
"country_name": "India",
},
{
"_id": 8,
"name": "Mohammad Ali Road",
"city_name": "Mumbai",
"city": 2,
"area": 24,
"country_name": "India",
},
{
"_id": 9,
"name": "Magarpatta",
"city_name": "Pune",
"city": 3,
"area": 31,
"country_name": "India",
},
{
"_id": 10,
"name": "Koregaon Park",
"city_name": "Pune",
"city": 3,
"area": 32,
"country_name": "India",
},
{
"_id": 11,
"name": "Rajajinagar",
"city_name": "Bangalore",
"city": 4,
"area": 41,
"country_name": "India",
},
{
"_id": 12,
"name": "Koramangala 6th Block",
"city_name": "Bangalore",
"city": 4,
"area": 42,
"country_name": "India",
},
{
"_id": 13,
"name": "Sector70, Chandigarh",
"city_name": "Chandigarh",
"city": 5,
"area": 51,
"country_name": "India",
},
{
"_id": 14,
"name": "Sector 28, Chandigarh",
"city_name": "Chandigarh",
"city": 5,
"area": 52,
"country_name": "India",
}
];
var cuisine = [abc];
app.get(`/`,(req, res) (function() {
res.status(200).send(“Api is running”)
}));
app.get(`/location`(req, res)(function () {
res.status(200).send(location)
}))
app.get(`/cuisine`(req, res)(function () {
res.status(200).send(cuisine)
}))
app.listen(port, (function (err) {
if (err) throw err;
console.log(`Server is running ${port}`)
}))```
Probably because of the Unicode quotation marks (“, ”) on line 123. Try replacing them with regular quotation marks (").

Processing array in JavaScript

So I have this javascript task, where I need to process data in an array. Suppose given array down below:
var data = [
/*Object 1*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg"
],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 2*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 4*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 5*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video"
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 6*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg"
],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
]
This array contains objects. So For each object we have:
personnelMateriaRel; videos; contactor (which includes: id, mobile, name, otherTel2, temobile, workUnit); pics; distributionResult(which includes: latitude, longitude, time, content, address); sendTime
Here i have two objects Jack (ID=18320) and Mike (ID=31903), you can see that each object repeats for couple time. It's because they have different "time". So the task is, return new array (or other data structures) which contains the objects with the last "time" (i.e. the biggest "time" value) and merge all "pics" and "videos", all objects that have been deleted, with the object with biggest "time" value. So for above example, the correct value to be stored would be:
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg" /*Merged*/
],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video" /*Merged*/
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg" /*Merged*/
],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
}
Here what I've tried so far, but the result still not correct:
function resolve(array) {
let map = {}
let keys = ["personnelMateriaRel",
"videos", "pics", "distributionResult",
"sendTime"]
array.forEach(element => {
let id = element["contactor"]["id"]
let eleTime = element["distributionResult"]["time"]
let object = map[id]
if (!object) {
object = map[id] = {
id: id,
time: eleTime,
}
} else {
let lastTime = object["time"]
if (new Date(eleTime) <= new Date(lastTime)) {
object["time"] = lastTime
}
}
for (let value of keys) {
object[value] = object[value]
? object[value].concat(element[value])
: [].concat(element[value])
}
});
return Object.keys(map).map(id => map[id])
}
Would appreciate any help!
UPDATE
So thnx to (#thingEvery)'s answer, according to his code, i get the result down below:
The "time" field is correct, but i still get returned all objects who's "time" was less than the biggest "time". The image shown is for the first Object (i.e Jack). So there is 4 Jacks, and it seems all the fields (contactor, distributionResult, sendTime) getting merged. All i need to be merged is "pics" and "videos".
If I'm understanding your question correctly, you were almost there. All I had to do to make it work was add "contactor" to your list of keys and fix your time comparison.
var data = [
/*Object 1*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg"
],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 2*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 4*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 5*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video"
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 6*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg"
],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
]
function resolve(array) {
let map = {};
let keys = ["personnelMateriaRel", "videos", "pics"];
array.forEach(element => {
let id = element.contactor.id;
let eleTime = element.distributionResult.time;
let object = map[id]
if (!object) {
object = map[id] = {
contactor: element.contactor,
distributionResult: element.distributionResult,
sendTime: element.sendTime
}
} else {
let lastTime = object.distributionResult.time;
if (eleTime >= lastTime) {
object.contactor = element.contactor;
object.distributionResult = element.distributionResult;
object.distributionResult.time = eleTime;
object.sendTime = element.sendTime;
}
}
for (let value of keys) {
object[value] = object[value] ?
object[value].concat(element[value]) : [].concat(element[value])
}
});
return Object.keys(map).map(id => map[id])
}
console.log(resolve(data));

Highcharts setData on pie chart not working

I am displaying a pie chart using the Highchart library. I have two sets of data I want to show, and I toggle between the two sets every 5 seconds indefinitely. When I load the initial set of data, the chart displays as it should. And when I load the second set of data (using setData), the chart changes as it should. However, all subsequent calls to setData seem to do nothing. I would expect the chart to change again and again corresponding to the new data. But nothing happens, and there are no errors logged in the console. What could I be doing wrong?
Here is my code:
var chart24HoursTop5;
var lastSet = 1;
var set1 = [{
"seconds": 754,
"y": 754,
"downtime": "00:05:07",
"siteNumber": "13",
"siteName": "Preston",
"name": "Preston",
"motorolaNumber": "SZ092C113",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "Wynn Communications",
"shelterOwner": "Wynn Communications",
"equipmentOwner": "DPS",
"latitude": "35.724833",
"longitude": "-95.988333",
"color": "#348AA7"
}, {
"seconds": 20,
"y": 20,
"downtime": "00:00:20",
"siteNumber": "29",
"siteName": "Bakers Peak",
"name": "Bakers Peak",
"motorolaNumber": "SZ092C129",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "FBI",
"shelterOwner": "DPS",
"equipmentOwner": "DPS",
"latitude": "34.839722",
"longitude": "-98.803333",
"color": "#ffa600"
}, {
"seconds": 19,
"y": 19,
"downtime": "00:00:19",
"siteNumber": "30",
"siteName": "Walters",
"name": "Walters",
"motorolaNumber": "SZ092C130",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "Cotton Electric",
"shelterOwner": "DPS",
"equipmentOwner": "DPS",
"latitude": "34.358583",
"longitude": "-98.321583",
"color": "#cb5464"
}, {
"seconds": 12,
"y": 12,
"downtime": "00:00:12",
"siteNumber": "69",
"siteName": "Hominy",
"name": "Hominy",
"motorolaNumber": "SZ092C169",
"system": "P25 GTR",
"channels": "",
"towerOwner": "Grand River Dam Authority",
"shelterOwner": "Grand River Dam Authority",
"equipmentOwner": "GRDA",
"latitude": "36.4",
"longitude": "-96.4863888888889",
"color": "#82F2C0"
}];
var set2 = [{
"seconds": 691,
"y": 691,
"downtime": "691 Sec",
"siteNumber": "13",
"siteName": "Preston 2",
"name": "Preston 2",
"motorolaNumber": "SZ092C113",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "Wynn Communications",
"shelterOwner": "Wynn Communications",
"equipmentOwner": "DPS",
"latitude": "35.724833",
"longitude": "-95.988333",
"color": "#348AA7"
}, {
"seconds": 10,
"y": 10,
"downtime": "10 Sec",
"siteNumber": "29",
"siteName": "Bakers Peak 2",
"name": "Bakers Peak 2",
"motorolaNumber": "SZ092C129",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "FBI",
"shelterOwner": "DPS",
"equipmentOwner": "DPS",
"latitude": "34.839722",
"longitude": "-98.803333",
"color": "#ffa600"
}, {
"seconds": 1,
"y": 1,
"downtime": "1 Sec",
"siteNumber": "30",
"siteName": "Walters 2",
"name": "Walters 2",
"motorolaNumber": "SZ092C130",
"system": "SZ Quantar",
"channels": "5",
"towerOwner": "Cotton Electric",
"shelterOwner": "DPS",
"equipmentOwner": "DPS",
"latitude": "34.358583",
"longitude": "-98.321583",
"color": "#cb5464"
}, {
"seconds": 5,
"y": 5,
"downtime": "5 Sec",
"siteNumber": "69",
"siteName": "Hominy 2",
"name": "Hominy 2",
"motorolaNumber": "SZ092C169",
"system": "P25 GTR",
"channels": "",
"towerOwner": "Grand River Dam Authority",
"shelterOwner": "Grand River Dam Authority",
"equipmentOwner": "GRDA",
"latitude": "36.4",
"longitude": "-96.4863888888889",
"color": "#82F2C0"
}];
$(document).ready(function () {
var optionsFor24HoursTop5 = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
credits: {
enabled: false
},
title: {
text: 'Last 24 Hours'
},
tooltip: {
pointFormat: '{series.name}: {point.downtime}'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '{point.name}: {point.downtime}'
}
}
},
series: [{
name: 'DropSum',
colorByPoint: true,
data: set1
}]
};
chart24HoursTop5 = Highcharts.chart("chartContainer", optionsFor24HoursTop5);
setTimeout(changeData, 5000);
});
function changeData() {
if (lastSet == 1) {
chart24HoursTop5.series[0].setData(set2);
lastSet = 2;
} else {
chart24HoursTop5.series[0].setData(set1);
lastSet = 1;
}
And here is a fully working jsFiddle example:
https://jsfiddle.net/mspinks/ksd8gjec/23/
You'll notice in the example that the chart displays initially, and then 5 seconds later, the data changes and is reflected in the chart display. However, the data changes again every 5 seconds, and none of those changes are reflected in the chart display. Why won't Highcharts show the updated data after the first change?
For performace Highcharts mutate the original data array, which causes that variables set1 and set2 are the same after the first update.
The solution can be to return the data by function:
function set1() {
return [...];
}
function set2() {
return [...];
}
function changeData() {
if (lastSet == 1) {
chart24HoursTop5.series[0].setData(set2());
lastSet = 2;
} else {
chart24HoursTop5.series[0].setData(set1());
lastSet = 1;
}
setTimeout(changeData, 2000);
}
Live demo: https://jsfiddle.net/BlackLabel/0smxjLac/
This does appear to be some sort of bug(?), but a workaround seems to be to specify that points should not be updated when setting the data. For example (JSFiddle):
function changeData() {
if (lastSet == 1){
// The fourth parameter makes or breaks the update
chart24HoursTop5.series[0].setData(set2, true, true, false);
lastSet = 2;
} else {
// The fourth parameter makes or breaks the update
chart24HoursTop5.series[0].setData(set1, true, true, false);
lastSet = 1;
}
setTimeout(changeData, 5000);
}
This does mean that there is no animation, as the points are scraped and new points are created. It does however appear that it is this updating of points that seems to stop the update from happening at all, so hopefully the main issue can be resolved as well.

Reading JSON file into javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
The last three hours i have been trying to read a JSON file into java-script for my map corodinates to be read by google-maps service.
I however,have an incomplete script..i can't get my results.Here is my script:
<script>
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'http://127.0.0.1/irismaps/aitems.php', true); // path to file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
results = JSON.parse(response);
for (var i=0; i<results[0].markers.length; i++) {
for (var b=0;b<results[0].markers[i].length;b++) {
//this is the object you are looking for
console.log(results[0].markers[i]);
break;
}
}
});
}
</script>
JSON:
{
"results": [
{
"markers": [
{
"longitude": "37.66653612499999",
"latitude": "55.77875861131171",
"title": "Industry LLC",
"icon": "img/markers/shop.png"
},
{
"longitude": "-82.28813722500001",
"latitude": "23.10569357133444",
"title": "Garden Care",
"icon": "img/markers/shop.png"
},
{
"longitude": "-4.792105912500006",
"latitude": "37.875266800953554",
"title": "Entertainers",
"icon": "img/markers/shop.png"
},
{
"longitude": "-73.94999999999999",
"latitude": "40.65",
"title": "Educators Corp.",
"icon": "img/markers/shop.png"
},
{
"longitude": "-0.8122895000000199",
"latitude": "52.0443456",
"title": "Rentacar",
"icon": "img/markers/shop.png"
},
{
"longitude": "4.879416200000037",
"latitude": "45.7783975",
"title": "Restaurant Lucia",
"icon": "img/markers/shop.png"
},
{
"longitude": "12.481953799999928",
"latitude": "41.90567180000001",
"title": "The Airport",
"icon": "img/markers/shop.png"
},
{
"longitude": "-74.0059731",
"latitude": "40.7143528",
"title": "Advertising Inc.",
"icon": "img/markers/shop.png"
},
{
"longitude": "12.7880859375",
"latitude": "4.565473550710291",
"title": "Car Repairs",
"icon": "img/markers/shop.png"
},
{
"longitude": "13.447265625",
"latitude": "52.53627304145948",
"title": "Accounting Gmbh.",
"icon": "img/markers/shop.png"
},
{
"longitude": "39.638671875",
"latitude": "24.447149589730845",
"title": "Courier & Courier",
"icon": "img/markers/shop.png"
},
{
"longitude": "10.7666015625",
"latitude": "59.93300042374631",
"title": "Your House A.S.",
"icon": "img/markers/shop.png"
},
{
"longitude": "-1.8896484375",
"latitude": "52.482780222078205",
"title": "M Supermarkets LLC",
"icon": "img/markers/shop.png"
},
{
"longitude": "21.005859375",
"latitude": "52.22779941887071",
"title": "Healthy Runner S.A.",
"icon": "img/markers/shop.png"
},
{
"longitude": "-0.8122895000000199",
"latitude": "52.0443456",
"title": "Rentacar",
"icon": "img/markers/shop.png"
},
{
"longitude": "-0.8122895000000199",
"latitude": "52.0443456",
"title": "Restaurant Lucia",
"icon": "img/markers/shop.png"
},
{
"longitude": "37.6173",
"latitude": "55.755826",
"title": "Industrie LLC",
"icon": "img/markers/shop.png"
},
{
"longitude": "-115.20111025",
"latitude": "55.80752971122906",
"title": "Book Group Inc.",
"icon": "img/markers/shop.png"
}
]
}
]
}
Try:
results.results[0].markers[i]
You are adding the entire file to an object called results that contains an array called results.
That JSON file you're trying to load is basically just JavaScript. Give your object a name like
var myJSONObject = {
"foo": "bar"
};
Save it as a .js file and load it into your document.

Categories