Displaying only the last version of an array - javascript

I want to display some data i'm getting from the database and I'm displaying them in an html text field, as such:
for(var i= 0; i < array.length; i++) {
document.getElementById("f1").innerHTML += array[i]+ "<br>";
}
however, i'm getting repeated results as you might already know that arrays get data like "data_one" "data_one, data two" "data_one, data_two, data_three" (not sure if there is a term for that sort of behavior) and the problem is that the data gets repeated when being displayed as well. I can't get the data first completely and then display the array either because I can't use the Firebase data outside of it's loop.
I know in android you can clear the recycler view adapter, so I was wondering if there is some sort of similar thing in javascript.

You can do document.getElementById("f1").innerHTML = '' before your loop, to clean your view.

Related

Iterating scraped data to return as a field objects inside an embed

I have a Discord bot that scrapes web data from inside an unordered list, the amount of list items in the ul can vary week by week from a minimum of 5 to a peak of 20.
I use this code to scrape the data (node.js and Cheerio):
$('li').eq(65).siblings().each(function(i, elem) {
details[i] = $(this).text().replace(/\*/g, ' ').split('/').join('or').trim();
});
My problem is because the number of list item elements can change on a weekly basis I never know how many addField objects to use when rendering the embed to Discord screen, so I can't add them by array index position as I would either have null values or not enough fields, I need to be able to generate addField objects so that each of the array index's returned is inside its own addField.
The embed is rendered with this code:
const embed = new Discord.RichEmbed()
.setColor(0xf1c40f)
.setTitle('Listing For The Week:')
.addField('Items', `${details}`)
.setTimestamp();
client.channels.get('546033223172620288').send({ embed });
This just displays the entire scraped data inside one field and it looks horrible as you can imagine, which is why I want to iterate the data into seperate .addFields.
I'm learning js so what do I have to do to get my desired outcome? I'm looking at doing something like this:
for (let i = 0; i < details.length; i++) {
.addField('ITEM:', details);
}
but I don't have the knowledge how to work with the .addField object and keep getting errors and finding that google isn't helping me find out how to approach this with the dot notation on addField inside a for loop.
You're one the right track I suppose. You can't simply have a "random" .addField() out there like that though. Simply utilize your existing embed variable within the loop - embed.addField('ITEM', details)

phaser.js - loading images in loop results in "Key not found in cache"

I'm trying to load dynamically created images into my phaser project from a JSON file.
the objects within the array all have the key "name" with a corresponding value of "box"+number
I'm loading them into the preloader like so:
var j = 0;
for (i in boxArray){
game.load.image(boxArray[j].name, 'collCreatorAssets/boxes/'+boxArray[j].name+'.png');
j++;
}
and trying to use them within my code like so:
j = 0;
for (i in boxArray){
var newBox = boxes.create(boxArray[j].xPos, boxArray[j].yPos, boxArray[j].name);
newBox.body.immovable = true;
newBox.destructable = boxArray[j].destructable;
j++;
}
logging the array to the console, I get no surprising bad news. the array containing the objects are working fine.
not surprising since the position I get from xPos and yPos respectively check out with the corresponding values within the objects in the array. resulting in properly placed image objects within the game. it's just not loading the images.
the images are also found on the server when loading them in the preload function, the only error I get is when starting the game:
Phaser.Cache.getImage: Key "box0" not found in Cache.
the parameters of the create function are
sprite.create(x,y,'key');
and the parameters of the load.image function are
game.load.image('key', 'path');
I've tested manually loading the images in the preloader and creating the sprites within the game using the loop and it works.
so I can narrow the issue down to the preloader but I don't see what I'm missing.
found the issue. I'm an idiot.
the loop was outside the success function of the request to get the JSON file.

Easier way to Populate Jstree with 6 levels

I have been working since last week with jstree for a project, and right now I am kind of stuck. I have been able to make it work with static data, but now I need to do it dynamically, and it needs to have up to 6 levels nested. Another condition is that the user should be able to just choose the deepest level, so I need to disable and make invisible the checkbox whenever a node has a children.
I am getting the data from SQL, but I am using a software called Thingworx to generate the user interface of the project (the tree is going to be a widget of for this software), so using JSON I think it's not an option.
My problem is that the only solution that I have found for now is something like this:
out:
var rowsActualData = core.data.rows.length
for (var i = 0, i < rowsActualData, i++){
if (Level1Value === core.data[i].text){
var rowsActualData2 = core.data.children.rows.length
for (var j = 0, j < rowsActualData2, j++){
if (Level2Value === core.data[i].children[j].text){
if (Level3Value !== null){
var rowsActualData3 = core.data.children.children.rows.length
...
All the levels of the code. Need less indent to be able to show it here
To check each case I need to check if the node exist already, go to the next level and check if exist, several times. And then, depending on each condition, I need to write it down as a new one or push it to one that exists already (for each level).
Part of the code for the first row, when the tree doesn't have data yet
Here an example of how it should look, but populating it with static data https://jsfiddle.net/josuenanin/LeyeLsrc/3/
Maybe I haven't explained myself too well, but not sure how to explain it without a lot of code.
Thank you in advance.

JavaScript using an array to display data

I'm working on a score system that shows per question block, I'm using PHP to retrieve the data from a table and the javascript below to calculate the score. The problem is I want several score labels underneath each question block. So clearly I need an array to make this work, but currently I'm using this line to write the data onto document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
so this only applies to the first entry in the array. How do I make it loop through the entire array(score_label[]) and increase it's value so the code reads document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1);
this is the element javascript is writing to
echo "your total score: <span id='score_label[0]' name='score_board['".$score_board."']'></span>";
if there is need for I can post the entire function but I think it's mostly my lack of knowledge on arrays that's the issue here
If I'm reading your question correctly (current_score is the same for all elements???):
for (var i = 0; i < score_label.length; ++i)
document.getElementById("score_label[" + i + "]").innerHTML=""+current_score.toFixed(1);
I should mention that the id attribute of the form score_label[N] may be confusing.
Try to use foreach function to loop through the whole score_label array.
need to loop through a PHP array in JavaScript

storing and retrieving 100-element array

I am using Greasemonkey/Tampermonkey to visit pages and make a change to a 100-element table based on what's on the current page.
Short term storage and array manipulation works fine, but I want to store the data permanently. I have tried GM_getValue/GM_setValue, GM_SuperValue, localStorage, and indexedDB, but I am clearly missing something fundamental.
Nothing seems to allow me to write the array into the permanent storage and then read it back into a variable where I can access each element, such that variablename[32] is actually the 32nd element in the table (Well, 33rd if you start counting at zero, which I do).
I need access to the entire 100-element table while the script is running, because I need to output some or all of it on the page itself. In the most basic case, I have a for loop which goes from 0 to 99, printing out the value of variablename[i] each time.
I have no predisposition to any method, I just want the frickin' thing to work in a Greasemonkey/Tampermonkey script.
Towards the top of the script I have this:
for (var i = 0; i <= 99; i++) {
currentData[i] = localStorage.getItem(currentData[i]);
}
The purpose of the above section is to read the 100 entries into the currentData array. That doesn't actually work for me now, probably because I'm not storing things properly in the first place.
In the middle, after modifying one of the elements, I want to replace it by doing this:
localStorage.setItem(
currentData[specificElementToChange], differentStuff);
The purpose of the above is to alter one of the 100 lines of data and store it permanently, so the next time the code at the top is read, it will pull out all 100 entries, with a single element changed by the above line.
That's the general principle.
I can't tell if what I'm doing isn't working because of some security issue with Firefox/Chrome or if what I want to do (permanently storing an array where each time I access a given page, one element changes) is impossible.
It's important that I access the array using the variable[element] format, but beyond that, any way I can store this data and retrieve it simply is fine with me.
I think you're going about this wrong. LocalStorage stores strings so the simplest way to store an array in LocalStorage is to stringify it into JSON and store the JSON. Then, when reading it back, you parse the JSON back into an array.
So, to read it in, you do this:
var currentData = JSON.parse(localStorage.getItem("currentData") || "[]");
To save your data, you do this:
localStorage.setItem("currentData", JSON.stringify(currentData));
Working demo: http://jsfiddle.net/jfriend00/6g5s6k1L/
When doing it this way, currentData is a variable that contains a normal array (after you've read in the data from LocalStorage). You can add items to it with .push(), read items with a numeric index such as:
var lastItem = currentData[currentData.length - 1];
Or, change an item in the array with:
currentData[0] = "newValue";
Of course, it's just a normal array, so you can use any array methods on it.

Categories