Create a "Dictionary" in javascript - javascript

In C# I have a Model with 2 properties and a Dictionary with a String key:
public class Model
{
public string Route { get; set; }
public string Template { get; set; }
}
Dictionary<String, Model> models;
The key is the model name and model is an instance of class model.
I need to create a similar structure in Javascript where I could Get an item from the "Dictionary" given a key or find if there is an item with a specific key in the "Dictionary".
Is something in Javascript that could replicate this?

You could create a function that would represent the random item in your dictionary:
function Model(route, template)
{
this.route = route;
this.template = template;
}
Then you could create an object like below:
var dictionary = {
"key1": new Model("route1", "template1"),
"key2": new Model("route2", "template2")
};
In JavaScript objects are containers for key/value pairs.
How we get the value for a specific key?
var model = dictionary["key1"];
or
var model = dictionary.key1;
If key1 isn't a key of dictionary, then you will get as model the undefined.
How we set the value for a specific key?
dictionary.key5 = new Model("route5", "template5");
What happens if there is already the key5 ?
You just assign a new value for this key. As it would happen, if we were in c#.
Above we used the constructor pattern, in order we create the values of our dictionary. This is a commonly used pattern for the creation of objects with the same properties.

In Javascript, a dictionary with string keys is just a plain object:
var models = {};
Add an element:
model.myKey = 'my value';
Get an element:
var value = model.myKey;
Check that an element exists:
if (model.myKey) { ...
(note that this will yield false for any Javascript falsey value, so if you store things like 0 or '' you should use the more pedantically correct method model.hasOwnProperty('myKey'))
Remove an element:
delete model.myKey;
You can also add elements when creating the object:
var obj = {
'an item': 1,
anotherItem: 'another value'
};
Note that keys can be accessed with a dot notation if they're valid Javascript identifiers:
var value = obj.key;
Or as values in brackets (useful if they're not valid identifiers or if you want to use a variable):
var value = obj['A key'];
var fromVar = obj[someVariableHoldingAKeyName];
(JSHint even has a rule that checks for that)
As for your model class, it could similarly be modeled as an object with keys 'route' and 'template', e.g:
var myModel = { route: 'my route', template: 'my template' };

The next version of ECMAScript introduces Map, which allows to use a value of any data type as key. Map is already supported in a variety of browsers.
Example:
var map = new Map();
map.set('foo', data);
map.get('foo);
As already mentioned, objects are also often used as dictionaries, and sufficient in most cases. However, some care has to be taken:
The default prototype of objects is Object.prototype, so they already contain some "default" entries (like toString or hasOwnProperty). This can be avoided by explicitly creating an object with no prototype: var dict = Object.create(null);
Similar to above, because Object.prototype can be extended, your "dictionary" could be changed as well without you knowing it. Object.create(null) solves that problem as well.

Similar to the other answers. You're probably well off to put your model into an Array (however you're getting them), and then looping through that array to create your dictionary object.
var models = {};
var m1 = {name:'Joe',age:25};
var m2 = {name:'Bill',age:30};
var m3 = {name:'Andy',age:50};
var arr = [m1,m2,m3];
for(var m in arr){
models[arr[m].name] = arr[m];
}
//console.log(models);
var joe = models.Joe;
var joe = models['Joe'];

Related

Store an object with an array inside?

Is there a way to store an object with an array[id] = "certain value", so that every single user has a list of favorite things ?
What I'm trying to achieve is having a data object with undefined values at first, and filling them in, so for example Jack and Sam could have an assigned favorite movie saved.
I tried something like this with no success:
Data.js:
module.exports = function() {
return {
favMovie: ""
}
};
App.js:
var person [] = data();
//1st person
person[811767132257839].favMovie = "Matrix";
//2nd person
person[107230716367889].favMovie = "Kill Bill";
//3rd person
person[973676332752239].favMovie = "Avatar";
...
console.log( "Favorite movie: " + person[id].favMovie );
It doesn't sound like you want any arrays at all, just objects.
// Create an object that we'll keep person objects in
var personData = {};
// Add a person object to it for person ID #123
personData[123] = {};
// Set person #123's favorite movie:
personData[123].favMovie = "Avatar";
// Add a different person; this time, we'll add the movie at
// the same time
personData[234] = {
favMovie: "Matrix"
};
When using objects as maps like that, sometimes people create the objects using Object.create(null) to avoid them having any inherited properties (like toString and valueOf and constructor):
person[123] = Object.create(null);
person[123].favMovie = "Avatar";
In ES2015 (aka "ES6"), you might want to use a Map rather than an object for the map of people:
var personData = new Map();
...and then use set and get for the individual person objects.
If the individual person objects get complicated, you might use a constructor function and associated prototype for them, using either ES5 syntax:
function Person() {
// ...
}
Person.prototype.doSomething = function() {
// ...
};
...or ES2015 syntax:
class Person {
constructor() {
// ...
}
doSomething() {
// ...
}
}
Then creating them:
personData[123] = new Person();
// or if using Map
personData.set(123, new Person());
Side note: Even when we write them as numbers, the keys (property names) in objects are always strings (unless you use ES2015 Symbols, which you probably wouldn't here). In contrast, keys in an ES2015 Map can be anything. Key equality in Map instances is determined using the special "same value zero" algorithm (which is basically === except that NaN is equal to itself [whereas it isn't in ===]).

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

C structure to JSON

I am very new to JS, have been working in C/C++ before,
I need an equivalent of below C structure in JSON
struct tmp_t{
int a;
char c_str[1024];
};
struct tmp2_t{
int a2;
.
.
char c2_str[1024];
};
struct my {
int number;
struct tmp_t tmp[100];
struct tmp2_t tmp2[100][1000];
};
For a json like
var myJSON = {
"number":0,
.
.
};
I need to access it like
myJSON.tmp[0].a = 10;
myJSON.tmp2[0][1].c2_str = "hello world"
any input is highly appreciated
Javascript properties are not typed like they are in C so there is no purely "equivalent" expression in javascript. You don't predeclare typed data structures like your C code has. I given variable or property in javascript can be assigned any value or reference - there is not hard typing. So without variables that can only contain a specific type like C has, there's no pre-declaring of data structure definitions like you have included from C.
Instead, you just declare the properties you want to use on a live object or if you intend to use many of them, you can create a prototype which you can instantiate when needed.
A direct declaration of a live object instance somewhat like your last structure would look like this:
var my = {
number: 10,
tmp: new Array(100),
tmp2: new Array(100)
};
This would declare an object named my that had three properties called number, tmp and tmp2. number initially contained the number 10 and the other two properties contained arrays of length 100 who's values were undefined. I don't know of any compact way to predefine your two dimensional array in javascript without running code in a loop to initialize it.
This data defintion would let you access my.number, my.tmp and so on.
If you want your arrays to contains objects with properties themselves, then you need to populate those arrays with the objects.
var my = {
number: 10,
tmp: [{a: 1, c_str: "foo"}, {a: 2, c_str: "whatever"}],
tmp2: new Array(100)
};
Or, in code, you could add in item to the tmp array with code like this:
var my = {
number: 10,
tmp: [],
tmp2: []
};
my.tmp.push({a: 1, c_str: "foo"});
my.tmp.push({a: 2, c_str: "whatever"});
Or, you could create the object separately and then put it in the array:
var obj = {}; // new empty object
obj.a = 1; // assign property
obj.c_str = "foo"; // assign property
my.tmp.push(obj); // put object into the array
obj = {}; // new empty bject
obj.a = 2;
obj.c_str = "whatever";
my.tmp.push(obj);
Or, you could assign each property individually like this:
my.tmp.push({}); // put empty object into the array
my.tmp[0].a = 1; // assign property to the object
my.tmp[0].c_str = "foo"; // assign property to the object
my.tmp.push({});
my.tmp[1].a = 2;
my.tmp[1].c_str = "whatever";
In either case, you could then access the data like this:
console.log(my.tmp[0].a); // 1
console.log(my.tmp[0].c_str); // "foo"

How to store objects in a array using javascript

i am developing extesnions for safari browswer. i want to store current active tab objects in a array as key. how to store multiple tab objects in a array.
i wrote following code.
**First scenario:
var obj = {};
obj1=new Object();
obj2=new Object();
obj3=new Object();
obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";**
prblem is i am getting 3rd object value. how to get all the object values.
**Second scenario:
var arr = new Array();
cTabObj1 = new Object();
arr[cTabObj1] = 'This is cTabObj1 Value';
cTabObj2 = new Object();
arr[cTabObj2] = 'This is cTabObj2 Value';
cTabObj3 = new Object();
arr[cTabObj3] = 'This is cTabObj3 Value';
alert("arr[cTabObj1] :" + arr[cTabObj1] + " arr[cTabObj2] :" + arr[cTabObj2] + " arr[cTabObj3] :" + arr[cTabObj3]);**
Here also i am getting "This is cTabObj3 Value" for all three object
Thanks in advance.
i want to store current active tab objects in a array as key
You can't do that. Keys are strings. They always are strings.
If you take a look at the array you will find any object gets converted to "[object Object]" so your basically inserting the same key 3 times.
Use console.log(arr) or console.dir(arr) together with firebug or chrome/opera/safari
What you want is a ES6 WeakMap.
Only Firefox6 implements WeakMap
The keys need to be strings.
Try implementing the toString method on your objects so that it returns a unique identifier for each object. Then 'cTab_' + obj will be a unique string.
You should rather store like this
cTabObj1 = new Object();
arr["cTabObj1"] = cTabObj1;
Your first scenario is the way to go except that you have assigned the same subscript key to each object that you are storing in obj. When you use anything other than a string for an object property key, the value has toString() called on it internally, so
obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";
will all have the same key of cTab_[object Object].
What you need is to differentiate the keys. Since each object will return "[object Object]" when toString() is called on it, you can remove the object from the property key too as it is redundant e.g.
var obj = {};
obj['cTab1'] = "This is object1";
obj['cTab2'] = "This is object2";
obj['cTab3'] = "This is object3";
or more tersely
var obj = {
cTab1 : "This is object1",
cTab2 : "This is object2",
cTab3 : "This is object3"
};
The reason why the second way is not the way to go is that you are trying to use a JavaScript array like an associative array, which they are not; it may seem to work at first but then you will discover some very odd behaviour, such as arr.length does not count them as items in the array, etc. For more details, read the linked article. You want to use Object ({}) for this.

How to access the properties of a JavaScript object?

while review a javascript coding, i saw that
var detailInf = {
"hTitle":"Results",
"hMark":"98"
};
What's the concept behind this js coding. While give alert for the variable its shows as "[object Object]". So this is an object, then how can we access the variable and reveal the data from this object.
Try doing this:
alert(detailInf['hTitle']);
alert(detailInf.hTitle);
Both will alert "Results" - this is a Javascript object that can be used as a dictionary of sorts.
Required reading: Objects as associative arrays
As a footnote, you should really get Firebug when messing around with Javascript. You could then just console.log(detailInf); and you would get a nicely mapped out display of the object in the console.
That form of a JavaScript object is called an object literal, just like there are array literals. For example, the following two array declarations are identical:
var a = [1, 2, 3]; // array literal
var b = new Array(1, 2, 3); // using the Array constructor
Just as above, an object may be declared in multiple ways. One of them is object literal in which you declare the properties along with the object:
var o = {property: "value"}; // object literal
Is equivalent to:
var o = new Object; // using the Object constructor
o.property = "value";
Objects may also be created from constructor functions. Like so:
var Foo = function() {
this.property = "value";
};
var o = new Foo;
Adding methods
As I said in a comment a few moments ago, this form of declaring a JavaScript object is not a JSON format. JSON is a data format and does not allow functions as values. That means the following is a valid JavaScript object literal, but not a valid JSON format:
var user = {
age : 16,
// this is a method
isAdult : function() {
// the object is referenced by the special variable: this
return this.age >= 18;
}
};
Also, the name of the properties need not be enclosed inside quotes. This is however required in JSON. In JavaScript we enclose them in brackets where the property name is a reserved word, like class, while and others. So the following are also equivalent:
var o = {
property : "value",
};
var o = {
"property" : "value",
};
Further more, the keys may also be numbers:
var a = {
0 : "foo",
1 : "bar",
2 : "abz"
};
alert(a[1]); // bar
Array-like objects
Now, if the above object would have also a length property, it will be an array like object:
var arrayLike = {
0 : "foo",
1 : "bar",
2 : "baz",
length : 3
};
Array-like means it can be easily iterated with normal iteration constructs (for, while). However, you cannot apply array methods on it. Like array.slice(). But this is another topic.
Square Bracket Notation
As Paolo Bergantino already said, you may access an object's properties using both the dot notation, as well as the square bracket notation. For example:
var o = {
property : "value"
};
o.property;
o["property"];
When would you want to use one over the other? People use square bracket notation when the property names is dynamically determined, like so:
var getProperty = function(object, property) {
return object[property];
};
Or when the property name is a JavaScript reserved word, for example while.
object["while"];
object.while; // error
That's an object in JSON format. That's a javascript object literal. Basically, the bits to the left of the :'s are the property names, and the bits to the right are the property values. So, what you have there is a variable called detailInf, that has two properties, hTitle and hMark. hTitle's value is Results, hMark's value is 98.
var detailInf = { "hTitle":"Results", "hMark":"98"};
alert(detailInf.hTitle); //should alert "Results"
alert(detailInf.hMark); //should alert "98
Edit Paolo's answer is better :-)
As Dan F says, that is an object in JSON format. To loop through all the properties of an object you can do:
for (var i in foo) {
alert('foo[' + i + ']: ' + foo[i]);
}

Categories

Resources