What is the difference between key and value in html cookies? - javascript

What is the difference between key and value in html cookies?
i saw that a cookie looks like this in html request:
not like this:
Cookie: name1=key1; name2=key2;
but rather like this:
Cookie: key1=value1; key2=value2;
and if a want to make a unique personal id for each cookie, say "UUID",
should i write key="UUID"? or value="UUID"?
im sorry for the "silly" question but im really confused here...
thank you!

a key-value pair is a way of storing information in an easily readable manner. You designate each piece of data (value) with a key, and reference the data with that key. So in your case, the string "UUID" would be the key, and the actual unique ID would be the value.
uuid=4dh26532gf564836fgf597g36
In your example, name1 would actually be the key, where key1 would be the value.
In layman's terms, the key is what comes before the equal sign (=), and the value is what comes after it.

Keys are the names of the variables and values are, well the actual value of them. So to use your example, the key/value pair would be UUID=12345

Key value pair is a convenient way of storing structured data: the key designates the kind of information (e.g. be it a name, an identifier, a URL, a path, a hash of some data etc) and value designates a piece of data of the designated kind (e.g. "John", "1247", "http://example.com/", "/data/file1.txt", "4858200518452f9b374549459d644042" etc).
Thus a key is metainformation, i.e. information about information since it describes the kind of information that follows it.
Structured data is easier to analyse and use by programs since it is immediately obvious which part of the data has what meaning.
Note that in your example syntax is unconventional: it should be key=value, i.e. your keys are name1 and name2 and values are key1 and key2.

Related

React how to address a key from string name

Ok, so I have a database with data sets in it. the application performs a base API call to retrieve that base data set containing all other data sets. I will receive a string variable with the name of the key I need to access so let's say const addon = "Book". However, I don't know the key name beforehand. So the following code works but I need to somehow not hard code the key parameter but rather use the string value incoming from the const addon. I am not quite sure how to do this please point me to the right documentation or explain how to achieve the wanted result.
const columns = levelOne.Book && Object.keys(levelOne.Book);
However, as the incoming param might not be "Book" but anything else it will only work for this case. It is guaranteed that there is a key-value pair where the key bears the name stored in the string value of addon.
You can use a variable as the key. For example, levelOne[variable] where variable is the string that you want to use as the key.
Also, you can get the keys through Object.keys(levelOne) and then you can set variable value from the keys array.

Is it possible to use ES6 Symbols in LocalStorage

When using a ES6 Symbol as the key for a key/value pair in LocalStorage, can we then still access it after reloading the page?
I found this tutorial that claims this to be possible when using Symbol.for, but so far I have no success and get an undefined when I try to retrieve the LocalStorage key/value pair.
As a side question: does it make sense to use Symbols over here?
You can use Symbols as keys in an object - that's one of theirs purposes. But localStorage is not your typical object. It has an API to set/get values in the store, which the tutorial you have shared is not using: localStorage.{set,get}Item().
Unfortunately localStorage doesn't accept Symbols as keys, only strings. So the real answer is no, you can't use Symbols as keys in LocalStorage, but...
You could do the following. It isn't actually using a Symbol as the key, but the Symbols toString() representation:
const sym = Symbol.for('Hello').toString()
localStorage.setItem(sym, 'World')
document.write('Hello, ' + localStorage.getItem(sym))
[ Check it out on jsbin.com ]
As a side question: does it make sense to use Symbols over here?
I suppose you could use reserved Symbols (e.g. Symbol.iterator) to extend the functionality of the localStorage global. But that's kind of besides the point.

Access element of dictionary in pug/jade

If I have a dictionary like:
x = {"A" : 1, "B" : 2 }
And I pass this dictionary into the pug file, how can I access a specific key value without iterating through all the elements in the dictionary?
For ex. x[A]
The only way I can think of right now is to iterate through the elements:
for key, val in x
And then have an if conditional in there that displays val when key equals A.
Am I missing something obvious here?
If you passes x dictionary to your .pug file you can simply show the key 1 of this dictionary using ${x.A}, same as in normal javascript.
Be sure to add back-tick between the expression.
every Javascript object is an associative array which is the most general sort of array you can invent - sometimes this is called a hash or map structure or a dictionary object.
An associative array is simply a set of key value pairs.
The value is stored in association with its key and if you provide the key the array will return the value.
This is all an associative array is and the name comes from the association between the key and the value. The key is a sort of generalized address that can be used to retrieve the stored value.
For example:
array={key1: 'value1',key2:'value2'};
creates an object called array with two keys and two values which in this case happen to be two constant strings.
Notice that the value stored can be any JavaScript object and in this example it is probably better to think of storing two string objects rather two string literals.
The key can be either an identifier, a string or a number but more about the difference in the key type as we progress.
You can retrieve a value via it key using array notation:
console.log(array['key2']);
Which displays the string value2. If you try and access a key that doesn't exist then you get the result undefined.
As the associative array is used to as the basis of the JavaScript object there is an alternative way to access a value that makes the key look like a property. That is you can access the value using "property syntax" as in:
console.log(array.key2);
So in jade/pug if you pass the x it will show you the similar result like in js. In your case it would be something like that:
${x["A"]} or ${x.A}

IndexedDB - What is Key, keyPath and indexName?

I am coming from MySQL and I am used to the conventional database table scheme. I am having trouble understanding IndexedDB and some of its terminology. I looked up these definitions in the documentation:
Key
A data value by which stored values are organized and retrieved in the object store.
indexName
The name of the index to create.
keyPath
The key path for the index to use.
Basically, Key is like a Primary Key in MySQL, right? Is indexName the same thing as a column? And I don't understand what a keyPath is.
Can someone explain these for me? Thank you again for you patience :).
Yes, key is like a primary key in SQL. But others seem to be missing an example explaining the main part of your question, and that is the distinction between indexName and keyPath. Per the Mozilla page on creating an index,
indexName
The name of the index to create. Note that it is possible to create an index with an empty name.
keyPath
The key path for the index to use. Note that it is possible to create an index with an empty keyPath, and also to pass in a sequence (array) as a keyPath.
The indexName is what you use to access that index. Indexes are used to search that "column" in the database.
The keyPath is the actual name of the "column." See other questions and answers for what forms a keyPath may take.
Note that "column" is not technically correct, but I'm using it because that's what you used.
For example, suppose your data has the column hours and you want to be able to search your database on that column. When creating your database you would create an index for that column:
objectStore.createIndex(indexName, keyPath, { unique: false });
where indexName can be anything you want, let's say hoursColumn, and keyPath would be hours.
objectStore.createIndex("hoursColumn", "hours", { unique: false });
unique: false just means that other rows of data may have the same value for hours.
I can write data to the objectStore as follows:
db.transaction(storeName, "readwrite").objectStore(storeName).add({hours: 20, minutes: 30});
So to search your data on the column hours, you could write:
var data = db.transaction(storeName).objectStore(storeName).index("hoursColumn").get(20)
and the result would be the first row of data where hours = 20, e.g. {hours: 20, minutes: 30}
So to summarize, indexName is just what you call the index you created that you want to search, and keyPath is the actual name of the stored data on which you want to search.
Indexes are a way to make it possible to query data in the indexeddb database. As you know objects are stored into the objectstores. These objectstore don't have a schema like you have in an normal SQL database.
An index exists out of 3 important properties:
indexName: The indexname is just a name you provide to the index. You will need this name if you want to use the index to query data.
keyPath: This defines which property of the object you want to address in your index. For example: you have an object
{ foo: "bar" }
and you want to query on the foo property, "foo" will be your keypath. The keypath can even go further. You can access nested properties
{ foo: { bar: "bla" } }
If you want to query the bar property the keypath will be "foo.bar"
key: The keys are the values inside the keypath. As you mentioned this key is unique for the index, but this doens't mean this value must be unique over all your objects in the objectstore.
The indexes in the indexeddb work like this:
When you create an index, it creates a new objectstore in which the object will be stored. Instead of storing these object bosed on primary key they are stored based on the values present in the keypath. This means that for a single key in an index you can have multiple objects. So if you start querying an index, it will filter on the keys and return the values that are present in these keys.
Hope this makes indexes clear for you.
I am updating my answer here having re-read the topic of Keys and Indexes. Coming from a MySQL background they are indeed confusing with IndexedDB.
(Please see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB#gloss_outofline_key)
Indexes
Typically these occur on elements within your "row" - so for example if you had a row:
{Hello:"World",Foo:"Bar} in your database you could set an index (of any name) on say Hello. This would be like your indexes in MySQL.
Keys
So where Indexes can have multiple, Keys must (as the earlier answer mentions) be unique like MySQL Primary keys. Why this gets confusing is that you can also filter/search your data by Keys as well as Indexes. (see https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) The difference appears that Key searches appear to be more Ranges (like A-F or > 5 AND < 10) rather than specific values.
There is a very interesting explanation here about keys:
https://golb.hplar.ch/2017/09/A-closer-look-at-IndexedDB.html#primary-keys
Basically it explains that there are 4 types of keys within IndexedDB:
out-of-line : you provide the key yourself on each insert
out-of-line auto generated : primary key (i.e. AutoIncrement) number generated automatically
inline : the contents of field form the index (this is typical to say a MySQL database but must then be unique)
inline auto generated: hidden field (visible in console) added and is accessible through code but not related directly to the object data.
The difference between 2 and 4 is that 2 doesn't get a defined Name, whereas 4 (like a Primary Key in MySQL) does. You could then update (but not insert) on the ID field you've named in 4.
On an aside I believe its called a Keypath because you can call field.subproperty which is quite nice. Please also make sure your keys are spelt correctly! Obvious mistake.
It was also hard for me to understand the difference, but at the end I found out and why most of the time we set them the same name.
In short, the indexName is how we want to the "field" or "column" (index) will be named in our "table" (Object Store) and the keyPath is the property of the stored object that contains the value of the field. Therefore, is logical that they have the same name.
For example, you have a table with following fields:
name
age
They both are the indexName of each field, but you have to tell IndexedDB which property (keyPath) contains the value of each field.
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("age", "age", { unique: false });
Key = Row Item
indexName = Column name
keyPath = Column name

How can I get the key as well as the value when using db.js to query IndexedDB?

I have an IndexedDB of changes. I add an item like this, and then log the result to check the key has been created successfully:
_this._idb.add('steps', step).done(function (items) {
var item = items[0];
_logger.log("ADDED STEP", { id: item.__id__, step: item }, "CT");
});
The output from this is as expected:
...as you can see, the id has been added to the object when it is stored.
However, when I query the db to getback a list of objects, using this code:
this._idb.steps.query('timestamp').bound(start, end).execute().done(function (results) {
_logger.log("Results", results, "CT");
}
I don't get the id as part of the object that is returned:
... and the lack of id makes updating and deleting impossible.
How can I get the id of the item when I query indexed db using db.js - or am I approaching this in the wrong way, and is there something else I should be doing?
(Note: I'm using TypeScript to compile the JS, but I don't think that's especially relevant to this question)
This is expected behaviour, you're only going to get the __id__ property if you don't define a keyPath in your db schema.
Because there's no keyPath defined the value is not associated with it in indexeddb, it's only added to the resulting object after it has been added, because at that point in time we know the auto-incremented value that IndexedDB has assigned to it.
Since the value isn't really part of the object I don't have any way to assign it to the object when it comes out during a query, maybe I could use the position in the array but that's more likely to be wrong than right.
If you want the ID to be persisted against the object then you need to define a keyPath as part of the object store schema and the property will be added to the resulting object and available and it will be on the object returned from a query.
Disclaimer - I wrote db.js
Looking at the source, __id__ is only defined when your keyPath is null in the add() method. From what I'm seeing, you'll never see this in a query() response.
In IDB null keyPaths are allowed only when using auto-incrementing ("out-of-line") keys. So if you're getting the object back, it should have an auto-incrementing key on it or some other keyPath.
The __ prefix in JavaScript usually means the developer intended it to be a "private" property. I'm guessing this is for internal use and you shouldn't be counting on this in your application code.
Consider using explicit, so-called "in-line" keys on your object store.
The goal of db.js is easy and simple to use. Your is advanced use case.

Categories

Resources