Reliably identify File Objects in JavaScript, like Hash or so - javascript

For uploading files in the Webbrowser, I implemented a file queue.
This is simply an Array that holds the file objects.
var filecache = new Array();
$(".fileinput").on("change", function (e) {
$.each(e.target.files, function (k, file) {
filecache.push(file);
});
});
Using this array, I need to have a function to remove specific files from that Array.
A File Object in JavaScript only contains a few properties: https://developer.mozilla.org/en-US/docs/Web/API/File
So when I want to remove a specific file from that FileObject-Aray, these are the properties I could use. But reliably is none of them. Two or more files in that Array can have the same name, so the name property will not be my choice.
I wonder if I could somehow create a Hash, a unique Key or something alike, out of the properties I have, to identify a specific file.
Is there a way to solve this problem? I know, Hashes are painful in JavaScript, but maybe someone knows another practical way.

You can add id property to file object and then put it to array.
id generation might be as trivial as function with state which returns incremented value or you can go even further and compute MD5 or CRC from the Blob.

Related

How to add an id property to a File?

I have an input to upload files. The uploaded files are shown as list displaying the file.name. When I add an id-property to a file it loses all it's properties except the path property. How can I add an id properly?
const fileWithId = {...uploadedFile, id: "myIdName"} //does not work
You can't copy File objects, they're largely-opaque data structures other than the specified properties, which don't include an id.
You might be able to just assign an id property (since most objects in the browser environment are extensible, meaning you can add properties to them), but I wouldn't recommend it. The definition of the File object changes over time, and you never know, it might get an id property that means something different from your id.
What you do instead will depend entirely on what you expect to do with the File. For instance, if this is just for client-side information, you might make your list a list of objects with id and file properties, where file is the original File object:
const fileWithId = {id: "myIdName", file: uploadedFile};

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.
One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.
var myArray = [];
function createArray(){
$.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
var obj1 = JSON.parse(data);
$.each(obj1, function(idx, obj) {
myArray.push(obj.name);
});
});
return true;
}
It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.
I want/need to convert this text input to a select dropdown using the Play! #select but the options arg for #select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).
If I manually create the List object, it works fine.
#select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))
The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the #select options.
I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.
Thanks in advance for the help.
You can not do that. And more precisely - you do not want to do that.
So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.
Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.
These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html.
Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.
Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

jQuery Id Selection and Dynamic Arrays

I have some code I'm struggling with. The good news is the code working as intended for a single instance; after some thought I've decided to feature multiple of these image selectors on a page. This works but the ugly approach of duplicating the code doesn't scale well (e.g. what if you want 50 of these on there?) The snag I've hit is how I can refer to a specific array. Is an array even an ideal solution for this?
The Objective
I have a series of images that a user may select from, up to X amount. The selected image ids are stored in an array and the image is added to a "selected images pool". This occurs by using an onClick for the slider, I obtain the Id from the element attributes. This is where I'm getting stuck.
var dataArray = $(this).closest("[id^=carousel]").data('array');
var slideCounter = $(this).closest("[id^=carousel]").data('counter');
slideCounter = dataArray.length;
The slideCounter returns the length of the string, not the array elements. How can I tell this code to refer to a particular array? See the fiddle for a better idea of the markup and code: jsFiddle
I have no doubt that there is a better approach. I'm relatively new to front end work, I'd appreciate any insights, I've burnt some brain cells on this, thanks!
From looking at your HTML, it looks like when you do this:
var dataArray = $(this).closest("[id^=carousel]").data('array');
what you're trying to do is to read the name of an array with .data() and then somehow turn that name (which is a string) into the array that's in your variable. My guess is that there's probably a better way to structure your code rather than putting javascript variable names in your HTML. I'd probably put a key name in the HTML and then store the arrays in an object where you can access them by that key name at any time.
Without trying to refactor your code, here's an idea for what you were trying to accomplish:
If selectedSlidesIdArray1 is a global variable, then you can do this:
var dataArray = window[$(this).closest("[id^=carousel]").data('array')];
Using the [stringVariable] notation on an object, lets you access a property by a literal string or a variable that contains a string. Since all global variables are also properties on the window object, you can do it this way for global variables.
If selectedSlidesIdArray1 is not a global variable, then you should probably put it in an object and then you can do this:
var dataArray = yourObj[$(this).closest("[id^=carousel]").data('array')];
Instead of trying to translate an arbitrary string into a JavaScript variable of the same name, why not just use another array? You can have nested arrays, which is to say an array of arrays.
Thus, instead of selectedSlidesIdArray1, selectedSlidesIdArray2, etc., you would have one selectedSlidesIdArray with sub-arrays, which you could then pull the index for using a data attribute.

unpacking GVariant in javascript

I have an array stored as a GVariant of type a(ss) in GSettings, that I want to use in a Cinnamon Applet. I can retrieve the value successfully using the following code:
let schema = schema_source.lookup(SCHEMA_NAME, false);
let settings = new Gio.Settings({ settings_schema: schema });
let my_value = settings.get_value('myvalue');
but I can't unpack it. As far as I can see, I will probably need to unpack it using a GVariantIter structure, but the documentation is limited, and I can't find the correct interface in the gjs API (if, indeed, it exists). Does anyone know how to do it?
Thanks!
edit:
my schema looks like this:
<key type="a(ss)" name="myvalue">
<default>[]</default>
<summary>an array of (string, string) tuples</summary>
<description></description>
</key>
For the time being I'm using an external JSON file to store settings, but it's not a 100% satisfactory solution. I suppose I could maintain two as-type variables, and keep them aligned, but there must be a way to do this properly, right?
A bit late, but my_value.unpack() works absolutely fine.
my_value.deep_unpack() will recursively unpack the arrays and their elements.
From your type of setting I guess you want to store/retrieve an array of strings? In this case, there is an easier method using Gio.Settings.get_strv(String key):
// Read the array (will create a real JS array):
let string_array = settings.get_strv("myvalue");
// Now do something with it...
// Store it:
settings.set_strv("myvalue", string_array);
Gio.Settings.sync(); // Important!
In your schema, you would then include an entry like this:
<key name="myvalue" type="as">
<default>[]</default>
<summary>Some array.</summary>
<description>An Array of strings.</description>
</key>
I use the same technique in my extension: Read/Write | Schema

Categories

Resources