How to give a custom name to the objects in an array? - javascript

I have an upload form and for adding and deleting the files in a filelist I created an array that contains the files to send them in one request.
Creating the array
var filelist = [];
for(var i = 0; i < data.files.length; i++){
filelist.push(data.files[i]);
console.log(filelist);
}
Result in console
[File, File, File]
The files are contained in the array but now I want to give the names in the array the names of the files for deleting purposes.
So instead of [File, File, File], I would like to have for example [image01.jpg, image02.jpg, image03.jpg]
I have already tried
filelist.push(data.files[i].name);
result
["image01.jpg", "image02.jpg", "image03.jpg"]
But the files aren't added to the array? Can anybody help me with this please?
The reason I'm doing this is because I would like to try to remove files from the array on value and not on index.
code for deleting the files from the array
var idx = filelist.indexOf(file.name);
filelist.splice(idx,1);

You can set the name of the file as a key:
var filelist = {};
for(var i = 0; i < data.files.length; i++) {
var file = data.files[i];
filelist[file.name] = file;
}
And then use the delete operator to delete the file based on its name:
var filename = fileToDelete.name;
delete filelist[filename];

Related

How to change JSON into string

i got a words array in JSON form like:
var words = [];
words.push({word:"I",x:50,y:50});
and i want it to store into a txt file which user can download from the website.
...
var data = JSON.stringify(words);
var file = new Blob([data],{type:'plain/text'});
...
however the output file is like this:
{"word":"Peaceful","x":40,"y":65,"lyric":"lyric"}
but i want it only print out the word "peaceful", i tried to use
var data = JSON.stringify(words.word);
but the output shows undefined.
words is an array, so you have to index it to access the object that you pushed onto it:
var data = JSON.stringify(words[0].word);
If I understand you correctly.
var myWords = [];
(for var i = 0; i < words.length; i++) {
var word = words[i].word;
myWords.push(word);
}
myWords.join(' '); // or myWords.join('\n');

How to merge 2 tsv files, based on a common value (in javascript)

I have 2 tsv files (tec00104.tsv & tec00114.tsv), with information about countries. I want to make one single array with the common countries from both tsv files. And the values that comes along. This doesn't seem to work, why?
// initialize array
var countries = [];
for(var i = 0; i < "tec00114.tsv".length; i++)
{
for(var j = 0; j < "tec00104.tsv".length; j++)
{
// if the country code is found in both tsv files
if("tec00114.tsv"[i][2] === "tec00104.tsv"[j][3]);
{
// append new value to the array
countries.push("tec00114.tsv"[i]);
countries.push("tec00104.tsv"[j]);
}
}
}
console.log(countries);
The problem, that you are trying to refer to filenames directly from JavaScript as an array. This is impossible in this way. You need to load them before (e.g. you can do it with $.get() function).
Or you can do it with Alasql library.
<script src="alasql.min.js"></script>
<script>
var countries = alasql('SELECT t1.*, t2.* FROM TSV("tec00114.tsv") t1 \
JOIN TSV("tec00104.tsv") t2 ON t1.[2] = t2.[3]');
</script>
If your TSV file has headers, use "headers:true" option, like below:
SELECT * FROM TSV("tex00114.tsv", {headers:true});

Sort input files after selection

Is there any way for me to sort files for POST to server using any client side solution?
More specific, i am using the following tag <input type="file" name="Myfiles[]" multiple> To choose some images.
With the code at the end i display a preview of the images and using jQuery UI sortable i'm able to change the position of the elements.
So, when i post the data to the server how can i insert the files in the order of the sort? that's the point where i'm stuck
for(var i = 0; i< this.files.length; i++)
{
var file = this.files[i];
if(!file.type.match(‘image’))
continue;
var picReader = new FileReader();
picReader.addEventListener('load',function(event){
var picFile = event.target;
$('#sortable').append('<li><img height="100" width="100" src="'+picFile.result+'" /></li>');
});
picReader.readAsDataURL(file);
}
Assuming you are storing the files into an array:
var storedFiles = [];
You can create a hidden field to store the IDs of the images in the order you want (3,1,2,4..) These IDs must be generated after your images are selected.
Then when the upload button is clicked, grab the sorted contents of the hidden input field and run a for loop to reprocess the order of the files.
var data = new FormData();
var items_array = $('.cvf_hidden_field').val();
var items = items_array.split(',');
for (var i in items){
var item_number = items[i];
data.append('files' + i, storedFiles[item_number]);
}
Then append the sorted files into the variable data, then send it using AJAX:
$.ajax({
url: 'upload.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false,
success: function(response, textStatus, jqXHR) {}
});
The order in which the server receives the files will be the order in which they were placed in the form to be submitted to the server.
That means it's probably easier to re-order them client-side before submitting e.g. by re-ordering the order in which they appear in the form for submission. Heres a rough-and-ready snippet of what you could use:
var newOrder = [];
for(var i = 0; i< this.files.length; i++){
var indiv_file = this.files[a];
// processing to calculate desired array position for submission
idealPos = function_returning_new_array_position(indiv_file);
newOrder[idealPos] = this.files[a];
}
Thus re-order your 'this.files' array to reflect your chosen order. And use the newOrder array in the form when you submit the files. I can't quite make out what you're doing in the above code, but unless your users are expecting their images to be re-ordered, it could turn out a bit disorienting to see the files they are planning to submit jumping around.
You can use plain JavaScript code to sort the files using the file names and store them as an array.
var files = evt.target.files
var RESULT = []
var m = files.length
for (var a = 0; a < m; a++) {
var min = 0
for (var b = 0; b < (m - 1) - a; b++) {
if ((files[b].name).localeCompare(files[b + 1].name) == 1) {
min = b + 1
}
}
RESULT[a] = files[min]
delete files[min]
}
The above code sorts the uploaded files in ascending order based on the file name and stores it in RESULT.

Javascript ignoring all files as opposed to one

I'm trying to get my javascript to ignore one file type extension that's held in a folder with a bunch of photoshop images. For all of the other file types in the folder I have it so that these file types populate a window and the user can import into their work space.
I have modified my script to ignore the file extension I want ignored, however it no longer populates the window with all of the other file types containted in the folder. But when I take out the file I want ignore from the folder, the window gets populated as it should.
This is what I have at the moment that checks my folder for the file types:
//Prompt for folder location
var Path = Folder.selectDialog("Select Folder Location for Renders")
// Use the path to the application and append the samples folder
var samplesFolder = Folder(Path)
//Get the files
var fileList = samplesFolder.getFiles()
//Creat Array to hold names
var renderTypes = new Array();
//Parse Initial name to get similar render elements
var beautyRender = fileList[0].name
beautyRender = beautyRender.substr(0, beautyRender.length-4)
//Get the render elements with a similar name
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Can anyone see what I've done wrong and need to modify?
Update
I'm still trying to get this to work and following the help from one of the posters below I have modified my code to the following:
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
renderTypes.push(fileList[i].name);
}
}
However, with this new code comes a new problem in that it returns every file contained in the folders and displays it.
I'm still stumped as to how I can get this to work as I would like. Please can anyone help me?
You're creating a sparse array, because you skip elements in renderTypes when you ignore a filename in fileList. That may be confusing your rendering code. Change to:
renderTypes.push(fileList[i].name);
What if :
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Wrong usage of the array
Missing ";"
Unnecessary use of "continue".
Managed to get a fix for this.
What I've ended up doing is creating a new function and passing that into my call for checking the folder locations.
function ignoreMe(f)
{
return f.name.match(/\.(stitchinfo)$/i) == null;
}
And the folder check:
var fileList = samplesFolder.getFiles(ignoreMe);

How can I remove the parent folders in an array of paths?

I am using the following code in order to retrieve sub folder names from the path declared. This works fine but how do I then remove the path name so that the array is a list of just folder names?
var myPath = Folder ("Z:/My File System/Me/Work Files/Design");
var folders = getFolders (myPath);
function getFolders(sourceFolder) {
var folderArray = new Array();
var sFolders = sourceFolder.getFiles ();
var len = sFolders.length;
for (var i = 0; i < len; i++) {
var sFolder = sFolders[i];
if (sFolder instanceof Folder) {
folderArray.push(sFolder);
}
}
return folderArray;
}
Instead of returning:
Z:/My File System/Me/Work Files/Design/One
Z:/My File System/Me/Work Files/Design/Two
Z:/My File System/Me/Work Files/Design/Three
Z:/My File System/Me/Work Files/Design/Four
I need:
One
Two
Three
Four
You could implement something like this (assuming you can modify the Folder prototype, and it stores the path as this.path):
Folder.prototype.basename = function () {
return this.path.split('/').pop();
};
You would then append the base names to the array:
folderArray.push(sFolder.basename());
You could use split() like this, assuming there are no other slashes towards the end.
var sample = 'Z:/My File System/Me/Work Files/Design/Four'.split('/')
var result = sample[sample.length - 1]
Regexp the string. Start at the end, and work backward until the first '/'

Categories