JavaScript Fetch API - save text as object? - javascript

I am currently working with the fetch API in JavaScript. I have a text file I'd like to read from called sample.txt. I would like to grab the different lines out of the text file and save it in an array so I can work with it. I've been searching for how to save it as an object, but I think I've been using the code for JSON and not for text. Please give any suggestions?
sample.txt
apple
banana
orange
grape
index.js
let fruitArray; //initialized new array
fetch('sample.txt') // fetch text file
.then((resp) => resp.text())
.then(data.split(/\r?\n/) = fruitArray)) //tried to assign each separate line as an element of fruitArray
Expected Output
fruitArray = ['apple', 'banana', 'orange', 'grape'];

let fruitArray; doesn't create a new array - you have to actually declare an array like [] for that. But it would be better to declare the array only once the response comes back, and then pass it around if needed.
.then accepts a function as a parameter, not a plain code block. The first parameter of the .then callback is the result of the resolution of the previous promise - which here is the full string.
When assigning (=), the left hand side needs to be a variable (or a property).
fetch('sample.txt') // fetch text file
.then((resp) => resp.text())
.then(data => {
const fruitsArray = data.split(/\r?\n/);
})

Related

Wanting to filter certain objects within an array before it returns the result, how would I properly use the .filter() function

I'm creating an order function app and the website I'm doing it for doesn't define all the tags in originally tags. For example, what I'm wanting to scrap is the size, but the the size as well as other fields within the same block are only defined by the <p> tag.
I have a function that collects all the objects within that block and pushes it into an array then pushed into an embed where it sends all the results. I've been trying to come up with a solution to pull on the "size" only within the block, but it returns null or sends the entire block. I read up that JS has a built in function called .filter() that potentially could be of use for this type of situation.
How would I go about approximately integrating the .filter() function to filter the other <p> tags out and only include that one I'm targeting?
Below I have attached my code for the size scraping as well as a screenshot of the HTML.
enter image description here
await page.waitForSelector(".responsive-body-3-2.mr12-lg.mb2-sm.pt3-sm.flx-gro-sm-1.flex-parent.d-sm-flx.flx-dir-sm-c.flx-jc-sm-sb.flx-ai-sm-fs");
let sizeInfo = await page.evaluate(() => {
let sizeTag = document.querySelectorAll(".responsive-body-3-2.mr12-lg.mb2-sm.pt3-sm.flx-gro-sm-1.flex-parent.d-sm-flx.flx-dir-sm-c.flx-jc-sm-sb.flx-ai-sm-fs");
let size = [];
sizeTag.forEach((tag) => {
size.push(tag.innerText)
})
return size;
});
console.log('Size has been collected!')

Highcharts data from a variable is not working but from works fine from an array

I am very new to JavaScript and Highcharts so thank you in advance. I am trying to create a simple chart using Highcharts. When I manuayy create the variable using this array the chart works:
let result = [1084.58,1084.65,1084.64]
However, when when I grab the data from JSON and put that into the variable the chart does not show the data. If I "alert" the variable that is created from the JSON is appears like this:
1084.58,1084.65,1084.64
I am guessing the format of the data from the JSON is not correct. What should I do to correct it?
When I use the manually created variable the chart appears correctly. When I create the variable from the JSON file the chart appears and the X axis has the correct labels but no data in the chart.
I did some testing and found what I think is the issue. The variable that is created from the JSON has quotes around each entry. How can I remove the quotes?
['1084.58', '1084.65', '1084.64']
You'll probably need to convert those values to Number type (using Number() or parseFloat()), you can do something like this:
variable => contains ['1084.58', '1084.65', '1084.64']
variable = variable.map(number => {return Number(number)})
Since you're new to Javascript (Welcome to this language!), I'm gonna explain how it works.
"map" is an array method which takes each element of an array and returns an value (simillar to forEach method, but forEach doesn't return anything). So when using map to return each element of an array like this you're pushing the new element to the new array, it will be something like
variable.map(number => {return Number(number)})
On the 1st element:
It returns Number('1084.58'), then it returns 1084.58 (number type)
On the 2nd element:
It returns Number('1084.65'), then it returns 1084.65 (number type)
On the 3rd element:
It returns Number('1084.64'), then it returns 1084.64 (number type)
Each return into this new variable is like an array.push(element)
Hope you got the idea

Axios how to get data inside of square brackets?

So I'm new with Axios and I'm trying to make a Discord bot that takes info from an api website and uses it. The issue is the data given looks like:
{"status":1,"size":1,"result":[{"number":"9999", and so on.
How do I get the data inside of the [ ]? I tried:
var teamNumber = response.data.result.number
but it doesn't work.
I can get response.data.status, but not result.number
TLDR: how to get 9999 from {"result":[{"number":"9999", ?
result is an array; if you want to get the first element from it (and get that element's "number" field) you'd do:
console.log(response.data.result[0].number);
If you want to loop over them you'd do:
response.data.result.map(el => {
console.log(el.number);
});

Does anyone know of a Javascript .csv file reader that will create an associative array?

It would be great to have a .csv file reader that can take a 'key' as an input to the reader to create an associative array.
I am reading a .csv file that looks something like this (simplified):
State,ID,Population
Alabama,AL,1234
California,CA,5678
Hawaii,HI,90123
North Dakota,ND,45678
etc...
And I would like to use a .csv file reader to allow me to do something like this:
csv_to_associatve_array("file.csv", function(foo,'ID') {
// Where ID is foo's "key" using the ID column of the csv file
// Then access foo as an associative array something like this:
console.log(foo['ND'].State)
});
This should log 'North Dakota' to the console.
I've searched quite a bit and can't seem to find anything. Maybe I'm using the wrong keywords.
In any case, if you have a neat way to access csv data using a key, that would be spiffy. Else, if no alternative, do you know a way to create an associative array from a 'normal' js array that a noob can understand and access as array[ID].State?
You can use d3.map() which creates a map, i.e. a key-value mapping, which is essentially what you are looking for. The neat advantage of using a d3.map over using JavaScript's built-in Map type introduced by ES6 is the fact that you can provide a key function to be used to extract the value for the key (ID in your case). The creation of the map becomes as simple as
const states = d3.map(data, d => d.ID);
You can then access an individual value, i.e. a state, by using states.get(key).
Have a look at the following snippet demonstrating the usage:
// Setup for loading of local csv data. Not relevant for answer.
const csv = URL.createObjectURL(new Blob([
`State,ID,Population
Alabama,AL,1234
California,CA,5678
Hawaii,HI,90123
North Dakota,ND,45678`
]));
// End of setup.
d3.csv(csv)
.then(data => {
const states = d3.map(data, d => d.ID); // Converts the parsed CSV data to a map.
console.log(states.get("ND").State); // > North Dakota
});
<script src="https://d3js.org/d3.v5.js"></script>

Can I convert a json input to a list of objects within jquery?

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

Categories