declare hashmap in javascript with <String,String array> - javascript

I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?

If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);

Related

JSON stringify does not convert array [duplicate]

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

Why does a string index in an array not increase the 'length'?

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

javascript push multidimensional array

I've got something like that:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
the result is [];
what am i do wrong?
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
Use []:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush as an object and push that onto cookie_value_add:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);

JavaScript arrays braces vs brackets

What is the difference between each of the following array definitions.
var myArray = [];
var myArray = {};
var myArray = new Array();
The first and third are equivalent and create a new array. The second creates a new empty object, not an array.
var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
var myObject = {}; is equivalent to var myObject = new Object();
So, the second example is not an Array but a general Object.
This can get confusing as Array is a class and Object is a class - more precisely Array is a sub-class of Object. So, by and large, Object semantics are applicable to an Array:
var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value'; // define a custom property.
console.log(o.property1);
console.log(o.length); // Outputs '2' as we've only push()'ed two elements onto the Array

What does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

Categories