save array values on reload and retrieve it back [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am pushing some random values into an array every minute.
On reloading I want to retrieve back this pushed content and keep pushing some random data every minute?
I am using local storage.
MyCODE--:
localStorage.setItem("test",Myarray.push(JSON.stringify(data)));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2); //var test is now re-loaded!
console.log(test);
This is not working.

Push the data to the array, then store it in the localStorage as JSON:
// Set
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));
Parse the JSON when you get the data back out (put this at the top of your script, or in your onload method):
// Get
if (localStorage.getItem("test")) {
Myarray = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
Myarray = [];
}
console.log(Myarray);

Local Storage works with strings only. Also, push returns the new length of the array, so the code you posted wont work as intended. Try this:
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));

The problem is you're storing the return value from .push() to local storage (which is the length of the array), instead of the actual data.
You should push to the array as required, then stringify the array and store.
var Myarray = [];
Myarray.push(....);
localStorage.setItem("test", JSON.stringify(Myarray);

Related

"Undefined" on my loop trying to fetch object in json file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Hi guys I'm having trouble in my for loop because there's a word "undefined" on the result of my loop, I'm trying to fetch objects on my json file and my loop works fine, I'm just wondering on how to remove the "undefined" word in my loop? thanks in advance.
here is the output
here is my code
and here is my json file
In your code, show variable before the loop is undefined, you haven't set some value for it, and using it without value. So, JavaScript can not identify the value of the variable and set it as "undefined"
Try this below:
var show = "";
for(var i=0;i<data.length;i++){
var obj = data[i];
show += "<div>"+obj["id"]+" "+obj["fname"]+"</div>"
}
$(".show").html(show)
Initialise your show variable with an empty string like azizbek mentioned.
let show = '';
If you don't want to, then use a condition to ignore it like this:
if (data[i] && data[i].id) {
let obj = data[id];
show += ...
}
Note:
I see that you use var in places that is not needed, inside a for loop or inside a callback. See this post for more info

transmitting "[]" string to php driven backend [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So theres a function which calls to backend which fetches all reservations in a certain timeframe and returns them to front-end. If there are no reservations in the respective timeframe, backend returns the string "[]". This data is then transmitted to backend again where I evaluate whether reservations exist or not.
For this, I want to use the php function "empty()" in backend.
And the code there basically just looks like this
$allReservationsOrRequestsByUser = json_decode($allReservationsOrRequestsByUser);
if(empty($allReservationsOrRequestsByUser)){
$overlapExists = false;
}else{
$overlapExists =
checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;
Now, I tried the above code both with and without decoding it before the if-condition. In both cases, "empty()" function always returns false, which shouldn't be the case when the array actually was empty.
What am I doing wrong?
you are trying to check if "[]" as empty. So it isn't empty as a string... You can convert it to a proper array before checking with empty() like...
$a = "[]";
var_dump(empty($a));
var_dump(empty(json_decode($a)));
that returns,
bool(false) <- Without Json decode
bool(true) <- With Json decode
You need to check array data in array or object
e.g if fetched array contain
if(empty($allReservationsOrRequestsByUser[0]['name'])){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
if object then use this and name is your database table column name
if(empty($allReservationsOrRequestsByUser[0]->name)){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;

iterate though JSON array in p5.js [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
I have a server that returns :
I want to iterate through this data in p5.js
var ms = []
function preload() {
var url ='https://dest/url'
ms = loadJSON(url)
}
Which I expected to return an array but it does not seem to return anything sensible.
However, if I paste the same data into the Javascript console I get different data :
How do I either iterate over this data (it is NOT loaded as an array) or convert it to an array?
I think you mean this:
var array;
for (var key in ms) {
if (!array) {
array = [a[key]];
} else {
array.push(a[key]);
}
}
console.log(array); // [ {'time': .... }, {...}, .. ]
You are getting an array of objects, Here's how you can simply iterate them
var data = [{"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"} ];
for(obj of data){
console.log("time and rate: ", obj.time, obj.rate)
}
jettpleyn had the only answer that actually worked in P5.
Eventually though - it dawned on me that I could make my life easier by changing the JSON returned from the server to an object containing an array rather than an array directly
{ "data":
[{"time":"85579.54189181328","rate":177.66287},{"time":"81978.61475682259","rate":177.66287},{"time":"78377.54175782204","rate":177.66287},{"time":"74776.58741879463","rate":177.66287},{"time":"71175.57481980324","rate":177.66287},{"time":"67574.59330582619","rate":177.66287},{"time":"63973.427922964096","rate":177.66287},{"time":"60372.39295697212","rate":177.66287},{"time":"56771.37366294861","rate":177.66287},{"time":"53170.276379823685","rate":177.66287},{"time":"49569.180530786514","rate":177.66287},{"time":"45968.02240085602","rate":177.66287},{"time":"42365.825628995895","rate":177.66287},{"time":"38764.64792180061","rate":177.71416},{"time":"35163.241872787476","rate":177.71416},{"time":"31562.00651884079","rate":177.72556},{"time":"27960.898827791214","rate":177.73126},{"time":"24359.687824964523","rate":177.67998},{"time":"20758.03328180313","rate":177.67998},{"time":"17156.808887004852","rate":174.53839},{"time":"13555.605601787567","rate":174.9276},{"time":"9954.546007871628","rate":175.35431},{"time":"6353.40945982933","rate":175.96582},{"time":"2752.3464789390564","rate":175.84541}]
}
As others have pointed out in the comments, what you have is essentially an array or an array-like object to be more precise and these can easily be converted to a proper array like so:
ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);
Looing at an issue in the p5.js github about this problem, more than one person suggest to do Object.values(ms) to transform the object into an array.
It has to be done after the preload function.

Javascript HTML localstorage [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 use localstorage to save items (songs) as favorites. But I would also like to be able to remove the items from the array, so not the key but the value of the key.
for example I have the key Songs and values of one , two, three. I would like to be able to remove two from Songs but one and three should remain.
I cant seem to figure out how to do so because all I can find is how to remove the key and not the value of the key.
Since you don't have any source code on display I will give you quick example of how to remove single values from the clients Local Storage. You can expand on this to remove multiple values. Wouldn't want to remove all the fun
I have commented out the Localstoage and created a Songs array so this will work in the snippet.
Remove /* and */ to uncomment that section and change getItem('Songs') to fit your current source code.
You will also want to remove var Songs[]; Snippet Use only
/*--Local Storage Use
// Get Songs from Local Storage
var Storage = localStorage.getItem('Songs');
//Split Songs into an Array
var Songs=Storage.split(',');
*/
// Snippet Use -- Example Values of the Songs Result
var Songs = ['Song One', 'Song Two', 'Song Three','Song Four'];
//------ Remove Single Value
var Remove = Songs.indexOf('Song Two');
alert('Old Songs List:\n'+Songs);
if (Remove > -1) {
Songs.splice(Remove, 1);
}
alert('New Songs List:\n'+Songs);
//--Update LocalStorage
//localStorage.setItem('Songs',Songs);
If you have any questions about the above example please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
Assuming your Object is structured like this;
"Songs": ["Song One", "Song Two", "Song Three"]
I don't have the code for you, but the process I would go through is;
Read localStorage item (localStorage.getItem('Songs'))
If you know the index of the item, you can then remove it. See this post for details
Re-save the Object to localStorage (localStorage.setItem('Songs', SongsObj)).
You need to get value of localStorage (Songs for example). Save value into variable, then change value (delete/remove some list items), then uses same key (Songs) set previous localStorage key with new value.
localStorage.setItem('Songs', [1,2,3,4,5]);
var songs = localStorage.getItem('Songs');
// ... some operations with list...
songs = [1,3,4];
localStorage.setItem('Songs', songs);

Object Obect array Json.stringify string array [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 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

Categories

Resources