Access element of dictionary in pug/jade - javascript

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}

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.

Acessing Object Elements

When I do
console.log(JSON.stringify(chunks1[1].data)))
This is the log:
"{\"data\":{\"0\":0.00006103515625,\"1\":0.00018310546875,\"2\":0.00018310546875,\"3\":0.0001220703125,\"4\":-0.0003662109375,\"5\":-0.000396728515625,\"6\":-0.000518798828125,\"7\":-0.00054931640625,\"8\":-0.00048828125,...
Now can I access the elements of "data"?
If I do
chunks1[1].data[0]
I get nothing. And
chunks1[1].data.1
Obviously I will get an error.
data is an object. Apart from getting the property with data.propertyName, you can also get it using an array notation, specifying the property name as a string. Like this:
chunks1[1].data['0']
#aduch makes a good point there. There is another 'data' in the output which I overlooked. The object with the numeric properties is actually a subobject, so the correct notation would be:
chunks1[1].data.data['0']
Currently, you are trying to access the elements of data as if it were an array, with numbered indexes, e.g. chunks1[1].data[0].
Instead, because data is an object, you should be using a string index: chunks1[1].data["0"].
And, because in your console.log example, chunks1[1].data is an object containing data as a key, your final accessing scheme should look like:
chunks1[1].data.data["0"]

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"]

How to use typed arrays to simulate objects?

Objects in JavaScript contain key-value pairs. The cost of a typical pair (using DevTools Profiler) is a reference to the key name, 8 bytes, and the cost of the object: 4 bytes for small ints, 8 bytes for numbers, references, etc.
The cost of the keys add up, especially in arrays with millions of objects.
Is there a asm.js sort of way to use typed arrays for arrays of identical objects?
Yes, I know this seems like a pain, but for a particular project, this may be required.
The sort of approach I'm thinking of is using a template JS object who's keys describes the offset into a typed array for each key's value, along with its type. For arrays of these objects, there'd be multiple of these object spans.
Thus two questions:
1 - Are my assumptions correct .. and there is no optimization in chrome/modern browsers that optimize the key costs? Possibly with constraints used here: http://www.2ality.com/2013/08/protecting-objects.html
2 - If so, is there a library for handling typed arrays as objects? Or any articles or gists etc?
If you have millions of objects, all with the same set of known keys and you have so many of them that memory is an issue, then you probably don't want to store your data as javascript objects at all.
You probably want to think about this like a database problem. You want:
A semi-compact storage format
A way to find the right record in the storage format (this depends upon what the data is and how you need to access it.
A way to read the semi-compact storage format and turn it into a live javascript object only when you want to actually use that object in your code.
A way to write changes back to the semi-compact storage format.
For example, if you had seven keys (e.g. fields) and three were numbers and four were strings and one of the numbers was your lookup key, then you could do this:
Create three typed arrays (one for each numeric value)
Create one regular array. This will hold all the string values concatenated together with a unique separator character.
Create a master key lookup object
As you read your data in, presumably from multiple ajax calls, you do the following:
Note the length of one of your arrays (they are all the same length) as this will be your new record number.
Add the lookup key to the master key object and set the value of the key to be the record number.
Add each numeric value to each typed array (each will be the record number index in the array)
Concat all the string values together with a separator between them in order by key and then put the contactenated string value into the string array.
Now you have a semi-compact storage format and a key lookup means. When you want to lookup a value, you use the master key lookup object. The value for the key will be the record number which is an index into the other arrays. You can create two functions that will find a record and return a javascript object form of the record (all data in key/value pairs on the object) and another function that will write an object (that might have changed = but the master key can't change) back to your storage format.
This makes a few assumptions about your data that you have one master key that won't change that you use for lookup and that you can find a separator to bind all the string values together and then separate them apart later and that you can know when you go to store all this and that you know what the keys are and that the objects generally all have the same keys.
If any of those assumptions are not true, then the design would have to be adapted to deal with that, but hopefully you get the idea of using something other than a giant array of objects to store your data and then constituting a given object only when you need to work with that record's data.

Trouble with "dictionary" creation in JavaScript

OK, first-off let me tell you that I'm too far from being considered experienced in JavaScript... (perhaps I'm even trying to implement something not actually supported by the language?).
So... here we are...
I want to create a structure like this (it's just an illustrative example) :
Addresses
--- John
--- Phone
--- Address
--- Peter
--- Phone
--- Address
So, I've seen (or perhaps I'm just guessing) that I can do something like that (I've run all my tests in Chrome's JavaScript console) :
var addresses = [];
addresses["John"] = {};
addresses["John"].Phone = "12312312312";
// And so on...
However :
If I do addresses['123'] = {}; then a proper 124-entry array is constructed.
If I do addresses['somestring'] = {}; then addresses remains an empty array [].
What am I doing wrong? Is there no native support for proper dictionaries (or map - no matter how this thing is called) in JavaScript?
Please note: I want to be able to progressively add entries to addresses, as well as keys to each address entry (and not just create it in one-shot).
You are creating an array, but then you are using it as an object instead (which is possible because an array happens to be an object). To contain properties rather than numbered indices, you should use an object:
var addresses = {};
addresses["Holmes"] = { Phone: "14", Address: "Baker street 221b" };
JavaScript has Objects and Arrays.
Arrays are a type of Object that treats properties with numerical with special significance. It will have a length property based on the highest value property name (that is a number), and it has methods such as push, pop and forEach to manipulate its numerical members based on their number.
If I do addresses['123'] = {}; then a proper 124-entry array is constructed.
You already have an array. That just adds a member called 123 to it and updates its length.
If I do addresses['somestring'] = {};
This will add that member to the array, but it won't appear in any of the regular means of accessing array members. You have to access it by name.
Don't give named properties to arrays. Use a plain object.
Is there no native support for proper dictionaries
An object is as close as you can get.
If you want something ordered use an array with numerical properties.
If you want something with named keys, use an object.
When you do this addresses['somestring'] = {}; you wil get an empty array because {} you are assigning an empty object.
Rather if you do addresses["dd"] = {s: "s"} the addresses will have the object
Javascript does not have dictionaries or maps or associative arrays.
It does, however, have objects which can be quite similar. (They can also be quite different, so that is essential to know.)
To make things more confusing, an array is an object. You can put random properties on an array and it will work -- like an object.
Javascript arrays take integer[*] indexes and adjust the .length property.
Objects take string property names. This is important: If you use something that is not a string, it will be converted into one .. usually called [Object object]
Might want to read this:
http://eloquentjavascript.net/chapter4.html
[*] Yea, yea, yea -- they are really strings behind the scenes. It is easier to think of them as integers and avoid that grief.

Categories

Resources