How to stock array with localStorage (Chrome Extension)? - javascript

I tried to stock an array in localStorage but then I read it was impossible. So I tried that:
array = {};
array.name = $('[name="name"]').val();
array.username = $('[name="username"]').val();
array.password = $('[name="password"]').val();
alert(localStorage['accounts']);
local = JSON.parse(localStorage['accounts']);
localu = local.push(array);
alert(JSON.stringify(localu));
In fact the scripts stops at the first alert which returns '[]' (I previously put that value to check the result).
Why isn't my script working?

JavaScript, {} is an Object. [] is an Array.
var array = [] and var array = new Array() do the same thing.
An array is an ordered container of stuff, each value has an index not a key.
An object is a named container of stuff, each "stuff" has a key.
Your array is definitely an object.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
alert(localStorage['accounts']);
// > undefined OR the value
local = JSON.parse(localStorage['accounts']);
// local contains a parsed version of localStorage['accounts']
localu = local.push(array);
// localu = 0 (push returns the length i think?)
alert(JSON.stringify(localu));
Try the following. I've not tested it, but might work.
var data = {};
data.name = $('[name="name"]').val();
data.username = $('[name="username"]').val();
data.password = $('[name="password"]').val();
if (localStorage['accounts'] == undefined) { // fixed
// does the key exist? No so create something to get us started
localu = { accounts: [] };
} else {
// the key exists! lets parse it
localu = JSON.parse(localStorage['accounts']);
}
// add the new "data" to the list
localu.accounts.push(data);
// save the results (we have to stringify it)
localStorage['accounts'] = JSON.stringify(localu);

Related

how to convert {obj:"{objects}"} into array with json object inside it

I had % in my cookie and I found following code for it and got the data below after implying that code
var cookies = (document.cookie);
var output = {};
cookies.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair.splice(1).join('='));
output[name] = value;
});
console.log(output);
The data console is down below;
{"objName":"[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]"}
I have the data as shown above, What I want is to objName into array and remove "" from in front of [] array barckets
objName=[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]
As far as I understand, you are trying to get cookie values, you can try this code and handle the returned array as you need. You can try this solution and let me know if it works.
var cookies = document.cookie.split(';').reduce(
(cookies, cookie) => {
const [name, val] = cookie.split('=').map(c => c.trim());
cookies[name] = val;
return cookies;
}, {});
console.log(cookies);

Function to format and add object to array not functioning properly

My component has a state array "bets" consisting of bet objects. The function in question creates an empty "records" array to house formatted records to be stored in the database.
const placeBets = () => {
//determine type of bet(s) - single,parlay,etc.
if(slipType === "single"){
let records = [];
bets.forEach(bet=>{
let tmpModel = formatSingleBet(bet)
records.push(tmpModel);
})
console.log(records);
}
}
I run a for each loop on the bets array to format each bet calling the formatSingleBet function.
//Function to format single bets in records for db storage
const formatSingleBet = (bet) =>{
//create instance of bet model obj and add properties
let betModel = model;
betModel.type = slipType;
betModel.wager = bet.wager;
betModel.odds = bet.odds.decimal;
betModel.result = "";
let legType = bet.type;
if(legType === "Spread"){
//create instance of spread line object
let spread = Spread;
spread.team.type = bet.team.type;
spread.team.name = bet.team.name;
spread.line = bet.handicap;
spread.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = spread;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "3-Way Moneyline"){
//create instance of ML line object
let ml = ML;
ml.team.type = bet.team.type;
ml.team.name = bet.team.name;
ml.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = ml;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "Total"){
//create instance of Total line object
let total = Total;
total.result = "";
total.bet = bet.bet;
total.line = bet.total;
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = total;
betModel.legs[0].odds = bet.odds.decimal;
}
return {
contestPlayerID: match.params.entryid,
jsonBet: betModel
};
}
I create an instance of the model object, and set the properties depending on the "leg type" of the bet. I then return the formatted bet to be inserted into the records array which is then returned.
The issue is that regardless of the differences in the bet, the betModel object is always returned as the last bet in the bets array.
One thing I noticed is that when I log the betModel it appears to be different for each bet, however the property values change when drilling into the object.
Please help, any advice would be wonderful.
By assigning betModel = model you are simply creating a reference to model and all the changes you make to betModel will also be made to model. This means that model is not a blank prototype, but contains the values of the last bet that you processed.
In order to use model as a prototype in the way you seem to intend use spread syntax to assign a copy to betModel.
let betModel = {...model}
const spreadSource = { a: 1, b: 2 };
const spread = {...spreadSource};
spread.c = 'Added'
console.log('spread: ', spread);
console.log('spreadSource: ', spreadSource);
const referenceSource = { a: 1, b: 2 };
const reference = referenceSource;
reference.c = 'Added';
console.log('reference: ', reference)
console.log('referenceSource: ', referenceSource)

How to add an element to multi-dimensional JSON array if the element key is a variable

There is a JSON file with an array like
{
"general_array":[
{"key_1":["a","b","c"]}
]
}
I want to add an element to the array e.g.
{"key_2":["d","e","f"]}
but the value of new key I get from a variable e.g.
var newKey = 'key_2';
I'm trying to add the element to the existed array as following
// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
jsonObj.general_array.push({newKey:['d','e','f']});
var newJsonFileContent = JSON.stringify(jsonObj);
// and rewrite the file ...
// console.log(newJsonFileContent);
But in the file I get
{
"general_array":[
{"key_1":["a","b","c"]},
{"newKey":["d","e","f"]}
]
}
i.e. as the new element key I get the NAME of variable, but I need its VALUE
How to add the value?
UPDATED
The solution with [newKey] works in most of browsers, but it doesn't work in Internet Explorer 11
I need a solution to be working in IE11 too, so the question is still actual
You can use [newKey] to get the value of the variable as a key name:
var jsonFileContent = `
{
"general_array":[
{"key_1":["a","b","c"]}
]
}`;
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);
var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);
To use the value of a variable as a JSON key, enclose it in square brackets, like so:
{[newKey]:['d','e','f']}
let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
let jsonObj = JSON.parse(jsonFileContent);
let newKey = 'key_2';
jsonObj.general_array.push({[newKey]:['d','e','f']});
let newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent)
This is the computed property name syntax. It's a shorthand/syntax sugaring for someObject[someKey] = somevalue
Try changing this line:
jsonObj.general_array.push({newKey:['d','e','f']});
For this:
var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);

Arrays and Localstorage

I'm having a little problem here, i have an array like this:
function crearObjetos()
{
var palabraPeso = "peso";
var palabraFecha = "Fecha";
var localStorageKey000 = "objetosPesoFecha";
var contador = 0;
var pesoFecha = new Array(); //THE ARRAY
while(contador < 365)
{
var nuevoObjeto = new Object;
var fechaActual = new Date();
nuevoObjeto.peso = 0;
nuevoObjeto.fecha = fechaActual;
nuevoObjeto.id = contador;
pesoFecha[contador] = nuevoObjeto; //SAVE OBJECTs IN THE ARRAY
contador = contador +1;
}
if (Modernizr.localstorage)
{
localStorage.setItem(localStorageKey000, pesoFecha); //STORAGE THE ARRAY
}
}
The problem is that, when i try to load the array in local storage, i can't acces any data, all are "undefined" and i don't know why... Here is how i load the data from the array (in this case only the first objetc):
function damePrimerObjetoPesoFecha()
{
//LOAD THE ARRAY FROM LOCAL STORAGE
var localStorageKey000 = "objetosPesoFecha";
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
//CHECK IN AN ALERT IF THE DATA IS OK
alert("El primero que devuelve"+arrayDeObjetos[0].id);
//RETURN THE FIRSTONE
return arrayDeObjetos[0];
}
An array can't be pushed into localStorage just like how it is. You have to use JSON.stringify on it. This line :
localStorage.setItem(localStorageKey000, pesoFecha);
must be changed to
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
Similarly, when you're retrieving it from localStorage, you must use JSON.parse on it to convert it back to JSON. This line :
var arrayDeObjetos = localStorage.getItem(localStorageKey000);
must be :
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
Now when you access the first data, you wont get undefined.
Another alternative to this would be jStorage plugin which is wrapper around localStorage. It will take all the parsing problems from you and do it by itself if you pass an array or object to it.
Hope this helps!
localStorage only stores data as string.
You can strinify your array into JSON and save that and then parse it back when you load it
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); //STORAGE THE ARRAY
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
LocalStorage can store strings only. You also need to remember that JSON.stringify converts date objects to string, so when deserializing via JSON.parse you need to manually create date for each object from array based on that string.
Firstly:
localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha));
and then
var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
arrayDeObjetos.forEach(function(objecto){
objecto.fecha = new Date(objecto.fecha );
})
localstorage can only store strings.
If you want to store arrays & objects, you should convert them to JSON.
Here's a small helper:
var LS = {
set: function (key, val) {
return localStorage.setItem(key, JSON.stringify(val));
},
get: function (key) {
return JSON.parse( localStorage.getItem(key) );
}
};
Use it as follows:
// Store the array:
LS.set(localStorageKey000, pesoFecha);
// Retrieve the array:
var arrayDeObjetos = LS.get(localStorageKey000);
Here's the fiddle: http://jsfiddle.net/KkgXU/

storing data in javascript

I want to iterate through a database and store the information as an array or object.
I don't really care which as long as I can store and retrieve based on a key.
I need guidence on the syntax to use to create and store data in javascript
// create storageEntity as array or objects
storageEntity = {};
storageEntity = [];
// on each retreival from data base store data in "storageEntity"
// conceptually it should look like this:
storageEntity[recordIFromFile][recordType][dataType] = value
where:
recordIFromFile - is an numeric value from file
recordType - is a string from file
dataType - is a string from file
value - is a numeric value from the file
You want to use an object/dictionary, i.e.
var storageEntity = {};
If your ID is 99999, you'd need 99998 empty entries in an array, I guess this isn't what you want. Now if you want to store a piece of data:
var record = storageEntity[recordIFromFile];
if (record == undefined) {
record = {};
storageEntity[recordIFromFile] = record;
}
var byType = record[recordType];
if (byType == undefined) {
byType = {};
record[recordType] = byType;
}
byType[dataType] = value;
Why can't you just request a JSON from your server and work over that instead?

Categories

Resources