Listing localstorage - javascript

I did my own feature using this:
function save(title, url)
{
for (var i = 1; i < localStorage.length; i++)
{
localStorage["saved-title_" + i + ""] = title;
localStorage["saved-url_" + i + ""] = url;
}
}
function listFavs()
{
for (var i = 1; i < localStorage.length; i++) {
console.log(localStorage["saved-fav-title_" + i + ""]);
}
}
save() happens when someone clicks on this:
onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';
However... it doesn't show the saved localStorages, how am I supposed to make it work?

Might it be because you are using the key 'saved-title_' + i to save the value and 'saved-fav-title_' + i to retrieve it?
The difference is the fav- part.
And your enumeration of the localStorage is bound to create errors as there is no guarantee that all items in it have a key that matches the pattern provided 'saved-fav-title_' + i - actually it is guaranteed to not be so as you are yourself inputting items with keys in the form of 'saved-url_'+ i.
So, if you want to properly enumerate the items with a key matching a pattern use
function listFavs(){
var key;
for (var i = 0, len = localStorage.length; i < len; i++){
key = localStorage.key(i);
if ((/^saved-fav-title_/).test(key)) {
console.log(localStorage.getItem(key);
}
}
}

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

How do I access children data in JSON response using Javascript/GAS

I am trying to access children data from a Json response to use it in an if statement but i don't know-how. Anyone know how to do this?
Here is the screenshot of the response and I have circled the object I want to access. I want only the summation to happen if the approval has a value i.e. status needs to be pending or approved, otherwise, no calculation will happen.
Here is the code that I use but don't know how to access the approaval={data=[{status}] form the JSON so as to use it
function showTimeData() {
var users = getUsers()
var endpoint = 'users/';
var time_array = [];
for (var i = 0; i < users.length; i++) {
var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
var total_hours = 0;
for (var j = 0; j < content.length; j++) {
if (content.data.approvals.data.length > 0) {
hoursTotal = 0;
}
total_hours += parseInt(content[j].hours);
}
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours)
}
First of all. You need to fix the error(mentioned in the chat in comments):
Replace this
if (content.data.approvals.data.length > 0) {
hoursTotal = 0;
}
with this
if (content[j].approvals.data.length > 0) {
hoursTotal = 0;
}
Then what you need is:
content[0].approvals.data[0].status
or an array of statuses:
content[0].approvals.data.map(el => el.status)
or an array of all statuses:
content.map(el => el.approvals.data.map(it => it.status)).flat(1)
but last example will work only in fairly new browsers.

How do you generate a previous and next button for an array?

I have a function with this specific array in it.
var elementsArray = xmlDocument.documentElement.getElementsByTagName('track');
// console.log(elementsArray);
var arrayLength = elementsArray.length;
var output = "<table>";
for (var i=0; i < arrayLength; i++)
{
var title = elementsArray[i].getElementsByTagName('title')[0].firstChild.nodeValue;
var artist = elementsArray[i].getElementsByTagName('artist')[0].firstChild.nodeValue;
var length = elementsArray[i].getElementsByTagName('length')[0].firstChild.nodeValue;
var filename = elementsArray[i].getElementsByTagName('filename')[0].firstChild.nodeValue;
console.log(title + ' ' + artist + ' ' + length + ' ' + filename);
output += "<tr>";
output += ("<td onclick='songSelect(\"" + filename + "\")'>" + title + "</td><td>" + artist + "</td>");
output += "</tr>";
}
With this array how would i generate a previous and next button to move.
http://jsfiddle.net/xbesjknL/
Once could use a linked list or even the notion of C-like pointers that point at the prev/curr/next tracks. But alas this is Javascript and the client side is too processing burdened.
So you could just build your own simplified idea of pointers in a cursor like object that is constantly pointing at the current track's index, the previous track's index and the next. And you'd call the refresh method everytime the user clicks the prev or next buttons to update the cursor's pointers accordingly.
var cursor = {
prev:(elementsArray.length-1),
curr:0,
next:(1 % (elementsArray.length-1)),
refresh: function(button){ //button is either the btnPrev or btnNext elements
if (button.getAttribute("id") === "btnPrev") {
old_curr = this.curr;
this.curr = this.prev;
if ((this.curr-1) < 0)
this.prev = elementsArray.length-1;
else
this.prev = this.curr - 1;
this.next = old_curr;
} else {
old_curr = this.curr;
this.curr = this.next;
if ((this.curr+1) > (elementsArray.length-1))
this.next= 0;
else
if (elementsArray.length === 1)
this.next = 0;
else
this.next = this.curr+1;
this.prev = old_curr;
}
}
};
// example usage:
cursor.refresh(btnPrev);
elementsArray[cursor.curr]; // gives the previous track, which is now the current track
You can even simplify this even more by just keeping track of only the current track. Note

What am I doing wrong in this javascript loop operation?

I've called some data from php using AJAX, and the result if I code alert(data.a) looks like this...
({a:[{my_id:"34", name:"Dave"}, {my_id:"39", name:"Barry"}]}
I'm not sure how to loop through this to extract the values.
My latest code...
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key]);
}
}
... displays
0 -> [object Object]
and this displays the same too...
for (var i=0, tot=data.a.length; i < tot; i++)
{
for (var key in data.a[i])
{
if (data.a[i].hasOwnProperty(key))
{
alert(key + " -> " + data.a[i][key]);
}
}
}
What's the trick to looping through these results to extract the data for display?
If it helps, here's what I send at the end of my php...
$x['a'] = $myArray;
echo json_encode($x);
Thanks for your time and help.
Are you after something like this? Loop through all the objects the print out all of their properties and values?
for (var i = 0; i < data.a.length; i++) {
var objectInArray = data.a[i];
var keys = Object.keys(objectInArray);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
alert(key + " -> " + objectInArray[key]);
}
}
When you are doing data.a[key] in for loop, you are getting a json object: {my_id:"34", name:"Dave"} for key = 0, and {my_id:"39", name:"Barry"} for key = 1. So in order to get values you should do something like this:
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key].my_id);
// data.a[key].name to get name attribute
}
}
Is it just
for (var i=0; i < data.a.length; i++) {
alert(data.a[i].my_id + " -> " + data.a[i].name);
}
In your example, data.a is an array of objects, so this would work:
for (var i = 0; i < data.a.length; i++) {
console.log('my_id: ' + data.a[i].my_id);
console.log('name: ' + data.a[i].name);
}

Jquery help needed- infinite loop?

i have a problem with this code:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
});
It causes ie and firefox to popup the warning window "Stop running this script". But it happens only when there is a very very large amount of data on page. Any ideas how to fix it?
Your code should look like this:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
}
});
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
There is no reason for the second loop to be inside the first - that will just cause a lot of unneeded work.
You can make this code a bit simpler by removing the par array and the second loop, and just creating the content inside the first loop:
$('.content').empty();
$('a[name]').each(function() {
var name = $(this).attr('name');
if (name.indexOf("searchword") == -1) {
$(".content").append('<a id="par" href="#' + name + '">' + name + '</a><br />');
}
});
Browsers run all javascript (and most page interaction) on a single thread. When you run a long loop like this with no interruptions, the UI is totally frozen. You should try to make your algorithm have to do less, but in case that's not possible you can use this trick where you do a bit of work, then pause and give the browser control of the UI thread for a bit, then do more work.
var $targets = $('a[name]');
var current = 0;
var i = 0;
function doSomeWork() {
if (i == $targets.length) return;
var $t = $targets[i];
if (($t.attr('name')).indexOf("searchword") == -1) {
par.push($t.attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
i++;
window.setTimeout(arguments.callee, 0);
}
This does one iteration of your loop in a function before yielding. It might be a good idea to do more than just one in a function call, but you can experiment with that. An article on this idea: http://www.julienlecomte.net/blog/2007/10/28/

Categories