Creating a Dart List from a Javascript array - javascript

I am trying to learn client-side Dart, coming from a server-side Java EE world, and I am having trouble converting an array from an existing JavaScript library into a Dart List.
I am trying to learn by building on the Javascript Interop example that uses Google Maps. In Google's Maps API's documentation, the DirectionsLeg object's step property returns.
array of DirectionsSteps, each of which contains information about the individual steps in this leg
How can I convert this var into a Dart List? I have tried the following:
final List<maps.DirectionsStep> steps = List.from(directionsLeg.steps);
But Dart Editor tells me cannot resolve method 'from' in class 'List'. My imports are:
import 'dart:html';
import 'dart:core';
import 'package:js/js.dart' as js;
What am I doing wrong? Is it even possible or must I just accept using a var?

There's no built-in way in js-interop for now to use Dart List when a js Array is returned.
directionsLeg.steps returns a js.Proxy which handles like js Array. You can iterate on it like this :
final steps = directionsLeg.steps;
for (var i = 0; i < steps.length ; i++) {
final step = steps[i];
// do the job with step
}
If you really want to use a Dart List you can convert the js.Proxy of js Array to a Dart List with something like :
List<js.Proxy> convertToList(js.Proxy arrayProxy){
final result = new List<js.Proxy>();
for (var i = 0; i < arrayProxy.length ; i++) {
result.add(arrayProxy[i]);
}
return result;
}
About your code :
You can't define List<maps.DirectionsStep> : maps.DirectionsStep is not a type, it's a js.Proxy on js google.maps.DirectionsStep (moreover it don't really exist - only a container js object {}).
List.from(...) : here, you try to call a static method named from on Dart List object. That why you get your error. List.from is actually a factory named constructor and has to be used with the new keyword ( new List.from(otherIterable) ).

Related

Undefined when parsing data and getting specific objects

I am using leaflet 1.7.1 and successfully loaded JSON file from the local memory of my machine.
I have an object which looks like this:
covid = {"AFG":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KOR":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KGZ":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
....}
What I want to do is to get countries by their ISO country code(e.g. KOR, KGZ etc).
Even after converting to object file I cannot get by index like covid[0] but it is not working.
I am new to JS and cannot really handle the data.
Notice it's not called JavaScript Array Notation, but rather JavaScript Object Notation.
The problem: covid is NOT an array. It's an object. Here's a great read. To fix your problem, you refer to the actual name.
To use it in your project, you could loop through the object and use it like so:
for (let isoCountryName in covid) {
console.log(`${isoCountryName}`);
}
Here's a demo:
var covid = {"AFG":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KOR":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KGZ":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6}};
for (let isoCountryName in covid) {
console.log(`ISO country name: ${isoCountryName}`);
}

lua.vm.js object/array to table

I am using lua.vm.js to give users of my node application the ability to add features in realtime. For that I have some JS Classes that I want to give them in lua.
Now I have the problem, that some of my functions should return arrays or objects.
On Lua side it is translated to userdata. In the most cases this will work but not for a array that should be used in a ipairs/pairs function.
I now that "in ipairs" or "in pairs" is existing in lua.vm.js
The question is how can I write a function that returns an array in a way that lua.vm.js is using it as a table.
Some example Code:
on JS side:
let luaVM = require("lua.vm.js");
let l = new luaVM.Lua.State();
l._G.set("someExampleFunction", {
example: function(){
return [1,2,3,4,5];
}
});
on Lua Side:
local shouldBeTable = someExampleFunction.example()
-- this will not work because shouldBeTable is not a table
for key, value in pairs(shouldBeTable) do
print(value)
end
Is there a way how to do that or to write a helper Function like arrayToTable ?

Create an array of JavaScript objects from an existing array of objects

my first time posting a question here, so please let me know if I'm missing any information that is needed. Updated to include desired output.
I'm working on a google app script (basically javascript) and am trying to pull objects from an array of objects and create a new array of objects. I'm using the google base functions for getRowData (these can be found at : https://developers.google.com/apps-script/guides/sheets) to create my initial array of objects. This gives me a row of data similar (A JIRA export if anyone is wondering, with information cut):
{summary=Internal - Fix PuppetFile Jenkins Jobs, progress=1.0, issueType=Story, resolution=Done, timeSpent=3600.0, key=XXXXX-646, watchers=0.0, remainingEstimate=0.0, numberOfComments=1.0, status=Resolved, assignee=XXXXXXXX}
When I run my function:
for (var i = 0; i < issueList.length; i++){
rankList[i] = [issueList[i].summary,issueList[i].storyPoints,issueList[i].epicLink,issueList[i].fixVersions];
}
I get:
[Internal - Fix PuppetFile Jenkins Jobs, 3.0, null, null]
But what I want is:
{summary=Internal - Fix PuppetFile Jenkins Jobs, storyPoints=1.0, epicLink=StoryName, fixVersions=Done}
I'm not getting the key for the value, and I don't understand how the objects are constructed quite well enough to get it to transfer over. I looked at some examples of manipulating the key/value pairs but when I tried it on my own I just got a bunch of undefined. Thank you for any help you can provide.
What you want is probably something like this:
rankList = [];
for (var i = 0; i < issueList.length; i++) {
issue = issueList[i];
rankList.push({
summary: issue.summary,
storyPoints: issue.progress,
epicLink: issue.IDONTKNOW,
fixVersions: issue.resolution
});
}
I don't know what field goes in epicLink, since it wasn't obvious from your example. And I was just guessing about the other fields. But this is the general structure, you just need to make all the correct correspondences.
Use jquery each instead it's much easier to get the keys and value at the same time:
var myarray = [];
$.each(issueList,function(key,value){
console.log(key);
console.log(value);
value.key = key;
myarray.push(value);
});
console.log(myarray);

Is it possible to implement a js version of Haskell's unzip in a purely functional fashion?

I'm implementing a javascript ray-casting point-in-polygon algorithm in a purely functional fashion (no particular reason behind it).
I got stuck as i needed to get two arrays from a 2-dimentional array (replicating a list of tuples); something akin to Haskell's unzip.
Is it possible, starting from something like [[a,b],[c,d],[e,f]] to obtain [[a,c,e],[b,d,f]] without using procedural-style iterators?
(I know it's a trivial question, and I could just implement the function procedurally and then forget about it, but I was curious to know if there was a solution)
EDIT: To clarify, I know how to implement zip and unzip: I was wondering wether it might be possible to implement them without for loops and variable reassignments.
Your unzip is just a zip but with multiple arguments. The only reason most people don't just use the same function is that most of the time zip receives a variadic list of arguments instead of a array so you need to unpack things with apply in the unzip function.
In Dojo, the library I am using, they implement zip and unzip as
unzip: function(/*Array*/ a){
// summary: similar to dojox.lang.functional.zip(), but takes
// a single array of arrays as the input.
// description: This function is similar to dojox.lang.functional.zip()
// and can be used to unzip objects packed by
// dojox.lang.functional.zip(). It is here mostly to provide
// a short-cut for the different method signature.
return df.zip.apply(null, a);
}
zip: function(){
// summary: returns an array of arrays, where the i-th array
// contains the i-th element from each of the argument arrays.
// description: This is the venerable zip combiner (for example,
// see Python documentation for general details). The returned
// array is truncated to match the length of the shortest input
// array.
var n = arguments[0].length,
m = arguments.length,
i = 1,
t = new Array(n),
j,
p;
for(; i < m; n = Math.min(n, arguments[i++].length));
for(i = 0; i < n; ++i){
p = new Array(m);
for(j = 0; j < m; p[j] = arguments[j][i], ++j);
t[i] = p;
}
return t;
},
Note that zip receives multiple arguments so it is more like the Python zip and less like the Haskell one.
It should not be hard to conver this code to a "purely functional" style without variable assignments. Your existing code should already be handling the job of the first two fors in the example I posted (truncating the zip at the minimum length and iterating through the indices of one of the lists). All that is left is doing a similar thing for the third for - collecting the i-th value from a list of lists instead of collecting two values from two lists.

jQuery/Javascript pulling info from an object

I am trying to use the following code to create a list of client names from some json returned from an Ajax call.
The data is as follows:
{"status":1,"data":{"clients":[{"ClientID":"1","AccountID":"1","ClientName":"Access Loan Mitigation","Active":"1"},{"ClientID":"2","AccountID":"1","ClientName":"Big Time Business","Active":"1"},{"ClientID":"3","AccountID":"1","ClientName":"Bill Releford","Active":"1"},{"ClientID":"4","AccountID":"1","ClientName":"Bonnie Silverman","Active":"1"},{"ClientID":"5","AccountID":"1","ClientName":"Dear Holdings","Active":"1"},{"ClientID":"6","AccountID":"1","ClientName":"Calm Dental","Active":"1"},{"ClientID":"7","AccountID":"1","ClientName":"Eva Field","Active":"1"},{"ClientID":"8","AccountID":"1","ClientName":"First Independent Pictures","Active":"1"},{"ClientID":"9","AccountID":"1","ClientName":"Gallery 825","Active":"1"},{"ClientID":"10","AccountID":"1","ClientName":"Greenway Arts Alliance","Active":"1"},{"ClientID":"11","AccountID":"1","ClientName":"International Strategy Group","Active":"1"},{"ClientID":"12","AccountID":"1","ClientName":"Ramtin","Active":"1"},{"ClientID":"13","AccountID":"1","ClientName":"Spabro","Active":"1"},{"ClientID":"14","AccountID":"1","ClientName":"LMGA","Active":"1"},{"ClientID":"15","AccountID":"1","ClientName":"Main Street Business Association","Active":"1"},{"ClientID":"16","AccountID":"1","ClientName":"Rabbit Animation","Active":"1"},{"ClientID":"17","AccountID":"1","ClientName":"Rooms & Gardens","Active":"1"},{"ClientID":"18","AccountID":"1","ClientName":"Summertime","Active":"1"},{"ClientID":"19","AccountID":"1","ClientName":"Sue Shellock","Active":"1"},{"ClientID":"20","AccountID":"1","ClientName":"Susan Gates","Active":"1"},{"ClientID":"21","AccountID":"1","ClientName":"The Park Entertainment","Active":"1"},{"ClientID":"22","AccountID":"1","ClientName":"Unified Dispatch","Active":"1"},{"ClientID":"23","AccountID":"1","ClientName":"Westside Media Group","Active":"1"},{"ClientID":"24","AccountID":"1","ClientName":"YHD","Active":"1"},{"ClientID":"25","AccountID":"1","ClientName":"Discoverfire, Inc.","Active":"1"}]}}
and the code is like so:
for (var Client in o.data.clients) {
$('#list_container').append("<div>"+Client.ClientName+"</div>");
}
Not quite working, and I've tried a few different ways of accessing the ClientName property. Javascript isn't my strongest language, and getting data out of objects just kills me - used to PHP object and arrays.
I'm sure this is simple - can somebody show the right syntax?
Thanks!
Clients is an array so it's better to use jQuery's each on it:
$.each( o.data,clients, function(idx, client) {
// use client.ClientName here
});
That's not quite how the for loop works. An easier, more accurate, and more reliable way to tackle this is to use the traditional for syntax like so:
for (var i = 0; i < o.data.clients.length; i++) {
var client = o.data.clients[i];
$('#list_container').append("<div>"+client.ClientName+"</div>");
}
The for syntax you were using will work, but it's still iterating over indices (not values), and even then it's not limited to just the integer indices in the array — it could also include other properties defined on the array prototype, or even on the particular array object. Iterating using the boring i = 0 syntax is a far better option for traditional arrays like this.

Categories

Resources