Problem creating localStorage key dynamically using template literals - javascript

I am trying to save values to localStorage with keys that are created using template literals to create new a new string from an existing string and a variable as the key, and concatenation a string and a number as the value.
In the console, the strings appear to be formatted correctly for local storage, but when run it produces the error "
TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present."
*The snippet below throws a sandbox error rather than the one I receive in my local environment. Can anyone shed some light at what I'm doing wrong?
var tm="Charlotte Knights";
var cl ="AA";
var yr = 2019;
console.log(`"my${cl}", "${tm}_${yr}"`)
localStorage.setItem(`"my${cl}", "${tm}_${yr}"`)

localStorage.setItem(`"my${cl}", "${tm}_${yr}"`) passes one string to the setItem function. To pass two, you need to end the template literal prior to the comma, then start another after it:
localStorage.setItem(`my${cl}`, `${tm}_${yr}`)
// --------------------------^--^
Also get rid of the " within the templates, unless you want actual " characters in the key and value.

Related

Parsing Javascript cookie values and separating values

I'm still learning Javascript and I'm trying to parse a value from a cookie in a specific key:
I'm using this current line:
const cookieObj = new URLSearchParams(document.cookie.replaceAll("; ","&","|"))
cookieObj.get("LG_AFF_TRK")
LG_AFF_TRK is the key that I'm pulling the value from. Doing so creates the output value of the following:
1|2|3|4|5|6
Each number represented would be a value that will have a random number of characters -and- could possibly be empty but each section always be separated by the "|" symbol.
How can I pull a specific value? As an example question, what do I need to do pull value 3?
I'm trying to understand this logically and my guess is I have to create an array first?

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

Using a variable to name another variable javascript

In the process of making a discord bot using node.js and discord.js, I've come to a point where I want to create a new variable, in this case an object with one property (the string "server" and some string for a value.) To name said new variable, I want to use the server ID of the server I'm referring to here, which is stored in another variable. What is a way I can do this?
So far I've tried
eval("var " + serverID + " = {'server': 'test'}"), which gave me a syntax error: invalid/unexpected token on the second plus sign (replacing the object with a string still gave me the same error). Everywhere I've looked hasn't been helpful in explaining what is wrong with the eval function, and I'm confused as to how I would do this another way.
In case the first thing that came to your mind was restructuring how I'm working with variables and the types I'm using, whatever this outputs must let me add more information to this variable, which at least in my mind restricts me to using Objects and adding properties. I also store this variable to a JSON file later in the code which also restricts me to using either Arrays or Objects.
I'm going to guess that the eval fails because your serverID is a number (or a string that represents a number), so the statement would look like var 123 = {'server': 'test'}, which would give a syntax error.
In any case, a simple alternative would be to create a property on an object instead of a variable. Something like:
var myVariables = {};
//...
myVariables[serverID] = {'server': 'test'};
You could even add it to the global object, if it makes sense for your situation and you really need a global variable.
There is no good reason to to store a variable as the name of another variable. The simplest way to accomplish what you want, as you mentioned, is storing the serverID in the object.
Your syntax is correct, although you may want to ensure that your server ID is a legal JavaScript identifier.
var serverID = "asddkjkisdf";
eval("var " + serverID + " = {'server': 'test'}")
console.log(asddkjkisdf);
I would however recommend creating a data structure like an array of objects to store this information. In that case you wouldn't have to worry about the value of your server ID. E.g.
[{id: 'asdfasdf', server: 'test'}, ... ]

NaN When trying to print json values

I was trying to parse a json which I got as a response of querying connections in linked in.
when I do JSON.stringify in an array as a whole I can see values in console.log
but when I try to take individual values inside array I get NaN.
Why can I not get Individual values when I can see the array as a whole.
here is the code
var response = jQuery.parseJSON(data);
var person = response.person[0];
in the above code I am getting data as a response of an ajax call
person is an array inside, I can stringify the array as a whole.
if I do
console.log(JSON.stringify(person));
I will get
{"id":"someId","first-name":"someName","last-name":"someName, DMC-E, DMC-D","picture-url":"https://soempicture"}
but When I try to take it individually
console.log(person.first-name);
I get NaN , and trying to strigify it results in Null
am I missing something, should I do string split to get the values?
Thank you
You can't access the first-name property using period notation, as the name contains a dash.
The code will be interpreted as person.first - name, i.e. the person.first property minus the name variable.
Use the bracket notation for any property where the name can't be an identifier:
console.log(person['first-name']);
To access a key that contains characters that cannot appear in an identifier (-), use brackets, i.e.:
person["first-name"]

JSON string not being parsed in Javascript

I am trying to store digital signature in database via rails application.
I am using javascript plugin that will convert signature into JSON string. Next I pluck JSON string from params and stored in a variable. Now I want to regenerate the signature by giving the plucked JSON string to a reverse javascript function.
The reverse function works fine if I set a variable in javascript directly to the JSON string and pass it to the function. However it does not work when I assign the variable to my rails variable which stores JSON string. The value of JSON string is exactly the same in both cases.
In first case the typeof var shows obj.obj type correctly but in second case it shows as a string. I tired every trick to parse using JSON and Jquery but it does not work.
My rails controller :
#recipient_signature = params[:recipient_signature]
My view where I want to see generated signature using the JSON string.
var sig = "<%=#recipient_signature%>";
$(document).ready(function() {
$('.sigPad').signaturePad({displayOnly:true}).regenerate(sig);
});
The above case does not work even though the value in #recipient_signature is correctly formed JSON string.
But when I assign the same JSON string to sig like below it works...
var sig = [{"lx":55,"ly":25,"mx":55,"my":24},{"lx":55,"ly":25,"mx":55,"my":25}....'];
This JSON string is same as in #recipient_signature and shows up in <%=#recipient_signature%> correctly.
Javascript somehow does not recoganize it as an array in first case and does in second case... how to fix it?
You're wrapping your json in quotes and using the variable in html encoded form:
var sig = "<%=#recipient_signature%>";
Should be
var sig = <%=raw #recipient_signature%>;
Or you should parse the json:
var sig = JSON.parse('<%=raw #recipient_signature%>');
Remove the quotes. That is, change:
var sig = "<%=#recipient_signature%>";
to
var sig = <%=#recipient_signature%>;
That way when the browser receives it it will look like your second example that works.
Note that that isn't really using JSON, it is simply using your server-side code to output a JS array literal directly into the JS code.
My guess is your assignment to sig with double quotes around it is causing a problem - try single quotes.

Categories

Resources