I wanted to make a code that will easily save all variables. Normally i would need for 60 variables about 120 lines. Not very efficient. I decided to try to make one function with array to try to save all variables. It doesnt seem to work.
My problem is that loaded variables are string, but i need them to be float.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage[variablelist[i]] = window[variablelist[i]];
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage[variablelist[i]];
}
}
I have tried
window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];
Nothing has worked. It is still a string. Any ideas ?
First of all, it hurts me to see so much stuff stored on the window object like that. You should really give that a re-think!
LocalStorage is a way of storing a key-value pair to the browsers memory for access later. The only catch is that the value has to be a string.
You can get around this my using the JSON.stringify and JSON.parse function:
var objectToSave = {
key1: 'something',
key2: 'something else'
};
localStorage.setItem('myObject', JSON.stringify(objectToSave));
console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object
Otherwise, if you are set on saving all of the individual variables, you are not far off, you just need to use the getItem and setItem:
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], window[variablelist[i]]);
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage.getItem(variablelist[i]);
}
}
Use localStore.setItem() and localStore.getItem() to store and load items. Also use JSON.stringify() and JSON.parse() to convert objects to text, and then restore them back to objects.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
}
}
Related
I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all
I'm sure this is really simple, I just can't work out how to do it.
I want to dynamically make an array from one variable equal to another:
var pageID = document.getElementsByClassName('page_example')[0].id;
Let's say this returned an id of page_1
var page_1 = ['value1','value2','value3'];
var page_2 = ['value4','value5','value6'];
var page_3 = ['value7','value8','value9'];
var page_array = (then have the associated pageID's array here)
So in this example,
page_array would equal ['value1','value2','value3']
Instead of storing the array in separate variables, store them in an object with the ids as the key:
var pages = {
page_1: ['value1','value2','value3'],
page_2: ['value4','value5','value6'],
page_3: ['value7','value8','value9']
}
You can access the arrays as though the object was an assosiative array:
var pageID = "page_1";
var pageArray = pages[pageID];
Depending on what you would like to achieve, you can one of two or three methods.
What I consider the easiest method is an if/else statement:
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(0);
} else if...
Another method you can use, again depending on what your ultimate goal is, would be a for loop:
for (var i = 0; i < numOfDesiredLoops; i++) {
page_array = page_1.slice(0, i);
}
Or you could use a combination of both:
for (var i = 0; i < numOfDesiredLoops; i++) {
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(1);
} else if...
}
With more information on why you need this variable to change, I can give you a better answer.
edit: keep in mind the arguments of .slice() can be whatever you want.
I have a JSON array which is returned from my PHP ajax call. I need to loop through it and display all the information. I can not seem to get a method working. I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here.
my array is
[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]
The length of the array changes every time it is not always 6 items.
And the loop is going to go in my success handler. I just need help on how to access the data.
success: function(data){
}
You can use a simple loop statement:
success: function(data){
var i, l;
for (i = 0, l = data.length; i < l; i++) {
// access the object: data[i]
console.log(data[i]);
}
}
This is the most effiecient way.
You can just loop through the array:
success: function(data){
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var type = obj.Type;
var durable = obj.Durable;
var url = obj.Url;
// do work
}
}
You can use the array prototype forEach:
data.forEach(function(item) {
var type = item["Type"];
var durable = item["Durable"];
/*...*/
});
I've been working on this, and it's very nearly working. I have a feeling that the setInterval inside the loop is something that can't be done, or isn't working. Without the setInterval and the final 'if' statement, it loops through the elements perfectly and adds a className to each if I set it to. Here's my script if anyone can advise as to where I am going wrong:
(function() {
var localStorageID = document.getElementById('local-storage');
var inputTags = ['input', 'textarea', 'select', 'button'];
// Loop through all the input tags on the page
for(var i = 0; i < inputTags.length; i++) {
// Create a variable that matches input tags inside our #localStorage
var localStorageTag = localStorageID.getElementsByTagName(inputTags[i]);
var formData = {};
for(var z = 0; z < localStorageTag.length; z++) {
formData[localStorageTag[z].name] = localStorageTag[z].value;
}
localStorage.setItem('formData', formData);
if(localStorage.getItem('formData')) {
// Try to achieve something
}
}
})();
You cannot store objects in localStorage. They must be strings. Convert the object to a string using JSON.stringify(), then JSON.parse() the string when retrieving from localStorage.
EDIT: for example:
localStorage.setItem('formData', JSON.stringify(formData));
var fd= JSON.parse(localStorage.getItem('formData'));
if(fd) {
// Try to achieve something
}
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']