Reading in a local csv file in javascript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[EDIT] I solved the problem using D3, nevermind thanks!
So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:
"L.Name", "F.Name", "Gender", "School Type", "Subjects"
"Doe", "John", "M", "University", "Chem I, statistics, English, Anatomy"
"Tan", "Betty", "F", "High School", "Algebra I, chem I, English 101"
"Han", "Anna", "F", "University", "PHY 3, Calc 2, anatomy I, spanish 101"
"Hawk", "Alan", "M", "University", "English 101, chem I"
I eventually need do parse it and output something like:
Chem I: 3 (number of people taking each subject)
Spanish 101: 1
Philosophy 204: 0
But for now, I am stuck on just importing it into javascript.
My current code looks like this:
<!DOCTYPE html>
<html>
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/>
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
var splitResearchArea = [];
var textInput = document.getElementById('numb').value;
var splitTextInput = textInput.split(",");
for(var i =0; i<splitTextInput.length; i++) {
var spltResearchArea = splitTextInput[i];
splitResearchArea.push(spltResearchArea);
}
}
I've researched and found some helpful links on Stackoverflow like this, this, and this but I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?
But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!

Here is how to use the readAsBinaryString() from the FileReader API to load a local file.
Basically, just need to listen to change event in <input type="file"> and call the readFile function.
const fileInput = document.getElementById('csv')
const readFile = () => {
const reader = new FileReader()
reader.onload = () => {
document.getElementById('out').innerHTML = reader.result
}
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0])
}
fileInput.addEventListener('change', readFile)
<div>
<p>Select local CSV File:</p>
<input id="csv" type="file" accept=".csv">
</div>
<pre id="out"><p>File contents will appear here</p></pre>
jsFiddle

There are as many ways of accomplishing what you want as you could possibly imagine.
If I were doing this, I might start by splitting the input text into lines like so:
var lines = inputText.split('\n');
Then, I would extract the names of the headers from the first line.
You need a function to read the values from each line.
// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
var values = line[0].split(',');
value = values.map(function(value){
return value.replace(/\"/g, '');
});
return values;
}
var headers = getCsvValuesFromLine(lines[0]);
Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.
lines.shift(); // remove header line from array
var people = lines.map(function(line) {
var person = {};
var lineValues = getCsvValuesFromLine(line);
for (var i = 0; i < lines.length; i += 1) {
person[headers[i]] = lineValues[i];
}
return person;
});
If this all works, you should end up with an array of objects representing the values in each line in your CSV.
The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.
I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.
Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.
Always write
XXXX {
....
}
and don't write
XXXX
{
....
}

i use this library from google: https://github.com/evanplaice/jquery-csv/
First - u have to
$.get(ur_csv_file_path);
and then use guide from page

Related

Is it good to use rename object key in function parameters?

Im quite new to Javascript. When im trying to learn the destructuring, i accidentially found out that i can rename the variable and use the old one as linking word to make the function easier to read (for me).
function getWords({ beginWith: character, from: text }) {
return text.split(" ").filter(word => word.startsWith(character));
}
let msg = "Hello world.";
let words = getWords({ beginWith: "H", from: msg });
console.log(words);
However, I wonder if this has any side effects to the program or not and should I continue to use it?

Append to specific element data from JSON objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I seem to be having an issue with my JSON objects, which is unusual because I have one block of code I know works:
function gotoPassage(id) {
for (var i = 0; i < passages.length; i++) {
if (passages[i].id == id) {
if (passages[i].bgImage)
changeBGImage(passages[i].bgImage);
$("#passage").hide();
$("#passage").html(passages[i].content);
$("#passage").fadeIn(1000);
}
}
}
The above code works as expected, so I assumed the same logic and applied it to my other code, which - by the way - does not render correctly. This code currently looks something like this:
function showLoreHistory() {
$("#lore ul").html("");
for (var i = 0; i < foundLore.length; i++) {
var content = "<li><a href='javascript:gotoLore(" + foundLore[i].id ");'>";
for (var j = 0; j < lore.length; j++) {
if (lore[j].id == foundLore[i].id) {
content += lore[j].title + "</a></li>";
$("#lore ul").append(content);
break;
}
}
}
$("#lore").toggle();
}
The structure of lore and foundLore look like this:
var lore = [{
"id": 0,
"title": "The First War",
"image": "Images/The First War.jpg",
"pages": [{
"content": ""
}]
}];
var foundLore = [{
"id": 0
}];
I was thinking of iterating through the keys of each JSON object, but found that it looked ugly, and considering my previous logic for showing passages worked assumed that the same logic would work for my Lore, but it does not seem to.
I would come up with a JSFiddle but unfortunately I rely on too many local resources to get it working properly without sacrificing code, which would defeat the point of me explaining the issue.
EDIT: If I comment out the for loops in the function showLoreHistory, the page will render correctly as expected in the following image.
EDIT 2: What I am trying to do is get the values from the above JSON object and adding the values to HTML, under a div tag namely lore - which is hidden by default.
The Div tag, with its content, looks like this:
<div id="lore">
<h1>Lore</h1>
<ul>
</ul>
</div>
If you have any solutions regarding this, I would strongly appreciate it. Thank you.
this line
var content = "<li><a href='javascript:gotoLore(" + foundLore[i].id ");'>";
is missing a '+' after foundLore[i].id
Also, the toggle is probably not what you want. I think you should hide it at the beginning of the function, then show it at the end like in your other function where you show the image.
If you open developer tools (f12 or ctrl+shift+j) it will show you errors like that.
p.s. it took literally under 2 minutes to make a fiddle for me to find the problem.. Give it a shot next time.
http://jsfiddle.net/8cr9t1zy/2/
You have to hit the button twice because of the toggle() thing I mentioned above.

converting python code to javascript code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');

How to UnObfuscate, Obfuscated Javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I obfuscated my javascript code using this one http://www.javascriptobfuscator.com/Default.aspx but it seems I can' find way to back it to original code.. is there any way?
You can get back some of your code, but almost all function names will be lost and local variables tend to get replaced.
Take for example the default code at the link you provided:
ORIGINAL
function NewObject(prefix)
{
var count=0;
this.SayHello=function(msg)
{
count++;
alert(prefix+msg);
}
this.GetCount=function()
{
return count;
}
}
var obj=new NewObject("Message : ");
obj.SayHello("You are welcome.");
OBFUSCATED
var _0x5601=["\x53\x61\x79\x48\x65\x6C\x6C\x6F","\x47\x65\x74\x43\x6F\x75\x6E\x74","\x4D\x65\x73\x73\x61\x67\x65\x20\x3A\x20","\x59\x6F\x75\x20\x61\x72\x65\x20\x77\x65\x6C\x63\x6F\x6D\x65\x2E"];function NewObject(_0xa158x2){var _0xa158x3=0;this[_0x5601[0]]=function (_0xa158x4){_0xa158x3++;alert(_0xa158x2+_0xa158x4);} ;this[_0x5601[1]]=function (){return _0xa158x3;} ;} ;var obj= new NewObject(_0x5601[2]);obj.SayHello(_0x5601[3]);
STEP 1 - Decode variable array
Firstly we need to decode the variable array (the part that starts var _0x5601= and ends just before the first function). I find the easiest way to do this is to copy and paste the array into Chromes developer console. Just paste the whole line and hit enter, then in the console type the variable name and you'll get something like this:
["SayHello", "GetCount", "Message : ", "You are welcome."]
STEP 2 - String Replace code for variable array item
Next we employ the help of whichever programming language you'd like to parse this new array back into the js. In essence, take your newly decoded array, and perform a string replace the rest of the code. I had PHP handy, so i did this:
<?php
// decoded array
$_0x5601 = array("SayHello", "GetCount", "Message : ", "You are welcome.");
// rest of the obfuscated code
$code = "function NewObject(_0xa158x2){var _0xa158x3=0;this[_0x5601[0]]=function (_0xa158x4){_0xa158x3++;alert(_0xa158x2+_0xa158x4);} ;this[_0x5601[1]]=function (){return _0xa158x3;} ;} ;var obj= new NewObject(_0x5601[2]);obj.SayHello(_0x5601[3]);";
// loop over array
for($x = 0; $x < count($_0x5601); $x++){
// string replace on the code
$code = str_replace('_0x5601['.$x.']', '"'.$_0x5601[$x].'"', $code);
}
// output result
echo $code;
?>
STEP 3 - BEAUTIFY
Now, lets "beautify" the code using something like: http://jsbeautifier.org/
function NewObject(_0xa158x2) {
var _0xa158x3 = 0;
this["SayHello"] = function(_0xa158x4) {
_0xa158x3++;
alert(_0xa158x2 + _0xa158x4);
};
this["GetCount"] = function() {
return _0xa158x3;
};
};
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
STEP 4 - Regex replace array items with object notation
The last step is to perform one last replace, but this time we need to employ the help of regex. I use an IDE called Sublime Text 2 that has the ability to do find and replace regex (im sure most IDE's have this too).
The regex pattern i used looks like this \[\"([a-zA-Z0-9\-\_]+)\"\] to explain:
\[\" // code must start with ["
( // open capturing group
[a-zA-Z0-9]+ // match all characters a-zA-Z0-9 you may need to adjust this to include -, _ etc as needed
) // capture everything in this group
\"\] // code must end with "]
You want to replace anything that matches this pattern with .$1. Resulting in:
function NewObject(_0xa158x2) {
var _0xa158x3 = 0;
this.SayHello = function(_0xa158x4) {
_0xa158x3++;
alert(_0xa158x2 + _0xa158x4);
};
this.GetCount = function() {
return _0xa158x3;
};
};
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
It's not quite as pretty, and as i mentioned local variables have been replaced. But if you know your code it shouldnt be too difficult to understand what they are doing.

Use jQuery to reference other javascript

Basically Im working with Sharepoint, help me god!
Sharepoint does some crazy the things but Im hoping what I want to do can be achieved using jQuery.
Sharepoint is writing some image values into a table:
<script>
fNewItem = false;
InsertItem("http://dev_site/sites/Pictures/Waves.jpg",
"5",
"BlueWaves",
"jpg",
"1920",
"1080",
"/_layouts/images/icjpg.gif", fNewItem);
</script>
There are a number of these output by Sharepoint, this snippet is from a Sharepoint Gallery so I'd need to loop through the page to find all of these so that I can grab all of the images.
What I want to know is if there is anyway for me to grab these values using jQuery and then output them again?
You can use this code (LIVE DEMO) ... you may need to tweak the if() statement a bit to determine which <script>..</script> blocks you want to deal with or not.
$('script').each(function(){
var t = $(this).text();
if (t.indexOf('fNewItem')>0 && t.indexOf('CDATA')<=0){
var a = t.split(/[\r\n]+/); //Split on Line Break
for (var x = 0; x<a.length; x++){
$('#result').append(a[x] + '<br>');
}
$('#result').append('<hr>');
}
});

Categories