How To parseFloat() strings coming from an Observable? - arrays

I have an issue trying to convert text to number for geoloc coordinates.
My model is: A site with Id etc... and an Array of points as a property. I decided not to create a relationship between site and points.
So in my code:
points is declared like this:
points: Array<any> = [];
rectangles is declared like this (an Array of Arrays):
rectangles: Array<Array<LatLngLiteral>> = [];
I am "looping" on sites for a particular customer and am building the Array called rectangles to show it on google map. rectangle is composed by as many as Arrays that sites are coming from the DB. Here I have two sites and the rectangle Array is:
rectangles : [[
[
{"lat":44.841225,"lng":-0.580036},
{"lat":44.842236,"lng":-0.64696},
{"lat":44.805615,"lng":-0.63084}
],
[
{"lat":44.819868,"lng":-0.582811},
{"lat":44.853709,"lng":-0.483573},
{"lat":44.80696,"lng":-0.53299},
{"lat":44.80696,"lng":-0.629078}
]]]
The code to retrieve it is:
this.customerApi.getSites(this.currentUser.id)
.subscribe(response => {
this.sites = response;
this.rectangles.push(this.sites.map(s => s.points));
});
}
Sites is like:
sites :
[
{
"siteName":"Site de Marseille",
"siteAdress1":"rue de blabla",
"siteAddress2":"string",
"siteCodPost":"13010",
"siteTown":"Marseille",
"points":
[
{"lat":44.841225,"lng":-0.580036},
{"lat":44.842236,"lng":-0.64696},
{"lat":44.805615,"lng":-0.63084}
],
"id":"5d0ce7c4a06b07213a87a753",
"companyId":"5cd430745304a21b9464a219",
"customerId":"5cd430c65304a21b9464a21a"`
}
,
{
"siteName":"Site de Bordeaux",
"siteAdress1":"rue de la Garonne",
"siteAddress2":"string",
"siteCodPost":"31000",
"siteTown":"Bordeau x",
"points":
[
{"lat":44.819868,"lng":-0.582811},
{"lat":44.853709,"lng":-0.483573},
{"lat":44.80696,"lng":-0.53299},
{"lat":44.80696,"lng":-0.629078}
],
"id":"5d0cf65fa06b07213a87a754",
"companyId":"5cd430745304a21b9464a219",
"customerId":"5cd430c65304a21b9464a21a"}]
The format of my rectangles array is good as another array like this with value hand written in the code show the rectangle on Google Map. Except maybe the number of square brackets ...
I think this comes from data format.
So I tried: points: Array<LatLngLiteral> = []; and it does not work.
I have no idea where I could use the parseFloat() method to try (if necessary).
Does any one have an precious idea to help me please?

Bonjour,
There is no float type in typescript so what you can do is to create a function that check for the content of any string and then convert it if this is a float as below:
getFloatValue(val) {
if (val.indexOf('.') > -1) {
try {
eval(val);
return parseFloat(val);
}
catch(error) {
console.log('error');
}
}
return val;
}
You can use this with each property of your object like this:
let lat = getFloatValue(rectangle[0].lat);

Related

Cant figure out how to go through array in Swift and find specific data

Hello I have question about arrays.
I have an array with following data, also I have corresponding Struct for SpiritRelation():
var spiritRelations = [
SpiritRelation(relationName: "Thunder Lantern", relationSpirit1: "Razor", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Double resist +5%, ATK +1600", relationSpiritIcons: ["razor", "genie"]),
SpiritRelation(relationName: "Illusive Fantasy", relationSpirit1: "Heavenly Maiden", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellent strike +15%, Dmg Penetration +15%, Max HP +11500", relationSpiritIcons: ["maiden", "genie"]),
SpiritRelation(relationName: "Grand Demonlord Gathering", relationSpirit1: "Sand Golem", relationSpirit2: "Lamp Genie", relationSpirit3: "", relationSpirit4: "", relationStats: "Excellency Resist +20%, Double Dmg +5%, ATK +1600", relationSpiritIcons: ["golem", "genie"])
}
array which contains data which will be selected by user:
var selectedSpiritsForRelation = [String]()
array of type String because I put there values which corresponds to image names in Assets. I need that to display images
array where I want to keep found relations and use it to display all found relationStats in UI
var foundRelations = [SpiritRelation]()
My problems is:
lets say user has selected 2 spirits for example: selectedSpiritsForRelation["golem", "genie"]
I’m able to find and save correctly found relation by
let result3 = spiritRelations.filter{$0.relationSpiritIcons == (selectedSpiritsForRelation) } // = 3rd relation in spiritRelations[]
foundRelations.append(contentsOf: result3)
but after user select another one spirit and array become: selectedSpiritsForRelation["golem", "genie", "maiden"]
same code as for result3 does not work anymore, because how I understand it tries to filter exactly combination of 3, but my expectation is that 2nd relation from spiritRelation[] will be found also
and here is my problem, I cant figure out how to correctly go through spiritRelations[] and find all relations related to selectedSpiritsForRelation[] every time user selects new spirit
You need to use allSatisfy in your filter by checking that all relationSpiritIcons elements exists in selectedSpiritsForRelation
foundRelations = spiritRelations.filter {
$0.relationSpiritIcons.allSatisfy { icon in
selectedSpiritsForRelation.contains(icon)
}
}

Array .map() returning undefined

This is the structure of the array when I console.log it.
-[]
-0: Array(31)
-0:
-date: "2018-08-26T00:00:00-04:00"
-registered:
-standard: 0
-vip: 0
-waitlisted:
-standard: 0
-vip: 0
This is my code to map the date and the registered (two separate arrays):
this.data.map((value) => value.date);
this.data.map((value) => value.registered['standard']);
I either get an empty array or undefined when I log these. What am I doing wrong?
I want to use these for a chart using ChartJS where:
this.lineChart = new Chart(lineCtx, {
type: 'line',
data: {
datasets: [{
label: (I want the dates to be the labels),
data: (I want the list of standard registrants)
}]...
EDIT:
I've updated the way I get the data to show the following structure:
{
"registrationHistory": [{
"date": "2018-08-26T00:00:00-4:00",
"registered": {
"vip":0,
"standard":0
},
"waitlisted":{
"vip":0,
"standard":0
}
{
,...
}
]}
Your array is two-dimensional and map is iterating only the first dimension, i.e:
-[]
-0: Array(31) // first dimension
-0: // second dimension
-date: "2018-08-26T00:00:00-04:00"
...
This would look like the following JSON string:
[[{"date":"2018-08-26T00:00:00-04:00", ...}]]
Since you haven't provided a full example it's impossible to recommend the most applicable solution:
If you control the data source, remove the first dimension since it appears redundant.
Assuming you only want the first element of the first dimension, refer to that key:
this.data[0].map((value) => value.date);
If your data model is more complex than revealed in your question you'll need to figure out another approach.

How to print only some specific numbers in with JSON ,SWIFT?

1.I have this array and i want to extract only the "rate" values.
I want y Array to look like this
array = [6,355.1675 , 4,826.3112 , 5,429.8488]
[{
code = USD;
description = "United States Dollar";
rate = "6,355.1675";
"rate_float" = "6355.1675";
symbol = "$";
}, {
code = GBP;
description = "British Pound Sterling";
rate = "4,826.3112";
"rate_float" = "4826.3112";
symbol = "£";
}, {
code = EUR;
description = Euro;
rate = "5,429.8488";
"rate_float" = "5429.8488";
symbol = "€";
}]
It looks like you have JSON that contains an array of dictionaries.
Write some code that:
Decodes the JSON into native objects. At the simplest it would be converted to an array of dictionaries.
You could then write code that loops through the array, extracts the rate value for each array entry, and prints it.
As others have said, you could do this with a map statement, but if you're new to programming then the for loop approach is easier to understand.
If you array is called array, then you can do it this way:
array.map { print ($0["rate"] }

FullCalendar JSON not populating calendar

I think I am missing something. I have set up Full Calendar, and have the default version working, but now am adding my own JSON, and it is not.
Code in the calendar page is
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
defaultDate: '2017-09-12',
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
events: {
url: 'php/get-events.php',
error: function() {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
I am learning how to encode JSON as I go along, and I found a tutorial online that gave me some code that seems to work. I have amended the original code in get-events.php to read like this (snippet with DB details taken out)...
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
// Short-circuit if the client did not give us a date range.
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
// Parse the start/end parameters.
// These are assumed to be ISO8601 strings with no time nor timezone, like "2013-12-29".
// Since no timezone will be present, they will parsed as UTC.
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
class Emp {
public $id = "";
public $title = "";
public $start = "";
public $url = "";
}
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
echo json_encode($e);
$JAN->moveNext();
}
$JAN->moveFirst(); //return RS to first record
// Read and parse our events JSON file into an array of event data arrays.
$json = file_get_contents(dirname(__FILE__) . '/../json/events.json');
$input_arrays = json_decode($json, true);
// Accumulate an output array of event data arrays.
$output_arrays = array();
foreach ($input_arrays as $array) {
// Convert the input array into a useful Event object
$event = new Event($array, $timezone);
// If the event is in-bounds, add it to the output
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
// Send JSON to the client.
echo json_encode($output_arrays);
When I run the get-events.php page on it's own I get what I am assuming to be a correctly encoded JSON returned, one example in the array is ...
{"id":20,"title":"Executive Committee Meeting","start":"2017-05-01T00:00:00","url":"meeting_info.php?ID=20"}
Can anybody tell me what I have done wrong?
You need to run json_encode() on a complete array of PHP objects, not on each one individually. In your loop, add each Emp to an array, and then encode the array, when the loop ends.
If you look in your browser's network tab at the result of your ajax request, I think you're very likely to see a string of individual objects, but not wrapped in array (square) brackets, and not separated by commas, meaning the JSON is invalid. There's also a good chance there's an error message in your browser's console about the invalid data format. It's best to check this rather than assuming your JSON is correct. There are also online JSON validator tools you can paste it into, to validate the JSON in isolation.
Something like this should work better:
$events = array();
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
$events[] = $e; //add event to the array
$JAN->moveNext();
}
echo json_encode($events); //encode the whole array as a coherent piece of JSON
//P.S. no need to run moveFirst really, since the request is going to end, and discard the resultset anyhow. Depending on your data access technique, you possibly need to close the recordset though, to avoid locking etc.
What you need your code to generate (and what fullCalendar is expecting), is a JSON array - here's a simple example containing 2 elements (representing events):
[
{ "id":20, "title":"Executive Committee Meeting", "start":"2017-05-01T00:00:00", "url":"meeting_info.php?ID=20" },
{ "id":21, "title":"Another Boring Committee Meeting", "start":"2017-05-02T00:00:00", "url":"meeting_info.php?ID=21" }
]
The example code I've given above should generate an array which is in the same format as this JSON sample.

Finding and matching two strings in different arrays

I'm trying to pass two arguments into a script that looks through arrays with a lot of values.
Basically, I have a pretty big JSON file with around 15 arrays (google sheet data). I then want to take the 1st argument, which is one/multiple words and match it in the 1st array. And then I want to take index numbers in the 1st array and only look through those index numbers in the 2nd array for a string that matches the 2nd argument and return the strings and the index number for future use. For example:
sheetData = [ [ "1stArray", "other", "other" ], [ "2ndArray", "stuff", "2stuff", "stuff" "2stuff" ] ]
If I then would type in: node index.js other 2stuff. It is supposed to find the two "other" entries in the 1st array, then look at the "stuff" and the first "2stuff" in the 2nd array and then return both "2stuff" and the index number 2.
So far I've been able to find one of the strings matching the 1st argument in the 1st array, but not the other ones. Nor have I been able to even go through the 2nd array trying to find another string. Here is the code I've written so far for this:
let fs = {
help: config.help.failstack,
func: (client, message, args) => {
// E = Enhance, R = Repair/replace, D = re-enhance (degrade part),
let itemName = args[0];
let enhanceWanted = args[1];
debugger;
var a = sheetData.values[[0]];
var sheetItemName = a.indexOf(itemName);
if (sheetItemName === -1) {
message.reply('Command not formatted correctly.')
.then(msg => console.log())
.catch(console.error);
} else {
var sheetFailstack = a.indexOf(enhanceWanted);
message.reply()
.then(msg => console.log(`${msg}`))
.catch(console.error);
}
}
}
var sheetFailstack = a.indexOf[enhanceWanted];
should be:
var sheetFailstack = a.indexOf(enhanceWanted);

Resources