I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp
Related
I'm trying to generate a google form that has a few hundred options in a drop down.
I have all the name values in a single cell formatted as follows:
'user1','user2','user3'
It is set as in the code as follows:
var studentNames = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
When I use this variable as shown below it treats it all as a singe value instead of an array.
.setChoiceValues([studentNames])
Any help in where to go from here?
is it a string of words with single quotes and a comma to separate them? if so, you can just do a split on the comma
var s = data
var arr = s.split(",");
and now you will have an array of strings. not sure if this answers your question.
Thanks everyone for getting me pointed in the right direction.
Turns out split was just part of the answer, I had to turn it into a string first.
.toString().split(",");
getValues() returns an object, so you need to interact with it to get the string of values for your array.
Given you are selecting just one cell and so don't need to iterate through the object, try something like this:
var studentNamesObj = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
var studentNames = studentNamesObj[0][0].split(",");
I am attempting to load a large set of JSON files into an array to be referenced later but Node keeps stating they're undefined. I have code along the lines of:
var myarray = [];
(...)
var loading_num = 001; // will be incremented in a loop to load data
myarray[loading_num] = fs.readFileSync("data/" + loading_num);
(...)
var reference_num = "001"; // the number being used to pull the appropriate record
(...)
console.log(myarray[reference_num].name); // just testing to attempt to decipher why it doesn't work, I'll actually be using the data obviously
Each JSON file does have a value named name and I have not implemented logic to load all of them yet as I am still just trying to get one to work.
Am I misunderstading something about Javascript arrays or objects? What am I doing wrong? There's a lot of files and they can vary in number so I have to load them in some similar fashion.
You should parse the file contents so the raw data is converted into JavaScript objects.
myarray[001] = JSON.parse(fs.readFileSync("data/001"));
First of all. fs.readFileSync reads arbitrary files. If you know your file is JSON and you want to convert it to js you need to parse it using JSON.parse.
Then 001 is 1 if you want it to be a string wrap it with quotes '001'
Array indices starts from 0.
var myarray = [];
myarray.push(JSON.parse(fs.readFileSync("data/001")));
console.log(myarray[0].name);
Or
var myarray = {}; // use object
myarray['001'] = JSON.parse(fs.readFileSync("data/001"));
var reference_num = "001";
console.log(myarray[reference_num].name);
In my getOptions.jsp file, I have created a string with jstl.
<c:set var="options" value="Maximize,Redo,RemoveFormat,Save" />
This string should now be transformed into this format (which is, if I am correct, a multidimensional javascript array (or is it json?)).
[['Maximize', 'Redo','RemoveFormat','Save']]
I have to do this because this format is expected by a javascript method located in another .jsp (showToolbar.jsp),
function handleToolbar(options) {
//toolbar = [['Maximize', 'Redo','RemoveFormat','Save']]; the expected format!
toolbar = options;
}
So my question is, how do I transform the comma-seperated string 'options' into the format that is expected in the 'toolbar' variable in order to pass it from one jsp to the other and pass it as a parameter of the handleToolbar function.
Note: I guess it is not ideal to use javascript in a jsp but that I cannot change because I inherited the code.
Thanks alot in advance, I've been searching for hours for the solution and can't find it.
Simple:
var myString = "Maximize,Redo,RemoveFormat,Save";
var myArray = [myString.split(',')];
The result is an array that has 1 element in it. That 1 element is this array:
['Maximize', 'Redo','RemoveFormat','Save']
So, myArray is:
[['Maximize', 'Redo','RemoveFormat','Save']]
I'm getting all input texts in my HTML page by using this:
var inputs = data.context.find(':input');
$('#result').text(JSON.stringify(inputs.serializeArray()));
Then I have an JSON string with id and value of each input text.
I'm trying to do something similar but with all my spans. I have this in my HTML file:
<td class="name"><span>{%=file.name%}</span></td>
I can have as many <td class="name"> ... tags as I want. So I have to get the value of all of them and convert to an JSON string as I did with the input text above.
How can I do it?
this code snippet: $('.name span') will return an array of objects, so in order to get the text from each one you need to run on it as an array:
$('.name span').each(function(index,val){
//do something with val
});
you can see a reference to this method here.
Simple fiddle: http://jsfiddle.net/CMdBa/1/
Iterate over .name (or specifiy deeper if necessary), build your data structure (using data), and then convert it to JSON. Working example: http://jsfiddle.net/tLuPC/
Below is simulating id if you needed to obtain that as mentioned in your post. Using data- attribute to store info. Otherwise you can simply just obtain the name.
var data = [],
jsonData = null;
$('.name').each(function () {
var item = $(this);
data.push({
id: item.data('id'),
name: $('span', item).text()
});
});
jsonData = JSON.stringify(data);
console.log(JSON.stringify(jsonData));
You can use a map function to enumerate and format a collection.
var spanTextArray = $('td.name span').map(function(){
return $.trim(this.innerHTML);
}).get();
This will output an array of file names, you could easily modify the return to output an array of key value pairs.
I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON