What is the JavaScript equivalent function for CreateObject("Scripting.Dictionary")?
I have to convert following two statements from VBScript to JavaScript, anyone can help me to find a solution.
Set oInvoicesToCreate = CreateObject("Scripting.Dictionary")
If Not oInvoicesToCreate.Exists(cInvoiceID) Then
oInvoicesToCreate(CStr(cInvoiceID)) = ""
End If
var oInvoicesToCreate = {};
if(oInvoicesToCreate[cInvoiceID] === undefined){
oInvoicesToCreate[cInvoiceID] = "";
}
You probably don't want to check the hasOwnProperty method because you'll want to check if anything in the prototype chain has that property as well and not overwrite it. checking with the []s will let you know if any property on any prototype items have the property as well.
As bluetoft says in this answer, in Javascript you can use a plain object instead. However, there are a few differences between them that you should be aware of:
First, a Dictionary's keys can be any type:
var dict = new ActiveXObject('Scripting.Dictionary');
dict(5) = 'Athens';
console.log(dict('5')); //prints undefined
whereas any value used for a Javascript object's key will be converted to a string first:
var obj = {};
obj[5] = 'Athens';
console.log(obj['5']); // prints 'Athens'
From MDN:
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.toString() method, and use this result string as the new key.
Second, it is possible to set a Dictionary to treat differently cased keys as the same key, using the CompareMode property:
var dict = new ActiveXObject('Scripting.Dictionary');
dict.CompareMode = 1;
dict('a') = 'Athens';
console.log(dict('A')); // prints 'Athens'
Javascript key access via [] doesn't support this, and if you want to treat differently-cased keys as the same, you'll have to convert the potential key to lowercase or uppercase before each read or write.
For your specific scenario, neither of these differences matter, because the keys are numeric strings (1) which have no case (2).
Related
What’s the difference between “{}” and “[]” while declaring a JavaScript array?
Normally I declare like
var a=[];
What is the meaning of declaring the array as var a={}
Nobody seems to be explaining the difference between an array and an object.
[] is declaring an array.
{} is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.
The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.
When you declare
var a=[];
you are declaring a empty array.
But when you are declaring
var a={};
you are declaring a Object .
Although Array is also Object in Javascript but it is numeric key paired values.
Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.
So if you want Some values where you need to use numeric keys use Array.
else use object.
you can Create object like:
var a={name:"abc",age:"14"};
And can access values like
console.log(a.name);
var a = [];
it is use for brackets for an array of simple values.
eg.
var name=["a","b","c"]
var a={}
is use for value arrays and objects/properties also.
eg.
var programmer = { 'name':'special', 'url':'www.google.com'}
It can be understood like this:
var a= []; //creates a new empty array
var a= {}; //creates a new empty object
You can also understand that
var a = {}; is equivalent to var a= new Object();
Note:
You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.
they are two different things..
[] is declaring an Array:
given, a list of elements held by numeric index.
{} is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more # This Article
Syntax of JSON
object = {} | { members }
members = pair | pair, members
pair = string : value
array = [] | [ elements ]
elements = value | value elements
value =
string|number|object|array|true|false|null
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
[ ] - this is used whenever we are declaring an empty array,
{ } - this is used whenever we declare an empty object
typeof([ ]) //object
typeof({ }) //object
but if your run
[ ].constructor.name //Array
so from this, you will understand it is an array here Array is the name of the base class.
The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.
I'm not supposed to add elements to an array like this:
var b = [];
b.val_1 = "a";
b.val_2 = "b";
b.val_3 = "c";
I can't use native array methods and why not just an object. I'm just adding properties to the array, not elements. I suppose this makes them parallel to the length property. Though trying to reset length (b.length = "a string") gets Uncaught RangeError: Invalid array length.
In any case, I can still see the properties I've set like this:
console.log(b); //[val_1: "a", val_2: "b", val_3: "c"]
I can access it using the dot syntax:
console.log(b.val_1); //a
If an array is just an object in the same way a string or a number is an object, why can't (not that I'd want to) I attach properties to them with this syntax:
var num = 1;
num.prop_1 = "a string";
console.log(num); //1
I cannot access its properties using dot syntax
console.log(num.prp); //undefined
Why can this be done with array and not with other datatypes. For all cases, I should use {} and would only ever need to use {}, so why have arrays got this ability?
JSBIN
Because arrays are treated as Objects by the language, you can see this by typing the following line of code:
console.log(typeof []) // object
But other types like number literals, string literals NaN ... etc are primitive types and are only wrapped in their object reprsentation in certain contexts defined by the language.
If you want to add properties or methods to a number like that, then you can use the Number constructor like this:
var num = new Number(1);
num.prop_1 = "fdadsf";
console.log(num.prop_1);
Using the Number constructor returns a number object which you can see by typing the following line:
console.log(typeof num); // object
While in the first case:
var num = 1;
console.log(typeof num) // number
EDIT 2: When you invoke a method on a number literal or string literal for instance, then that primitive is wrapped into its object representation automatically by the language for the method call to take place, for example:
var num = 3;
console.log(num.toFixed(3)); // 3.000
Here num is a primitive variable, but when you call the toFixed() metohd on it, it gets wrapped to a Number object so the method call can take place.
EDIT: In the first case, you created a string like this first var str = new String(), but then you changed it to str = "asdf" and then assigned the property str.var_1 = "1234".
Of course, this won't work, because when you assigned str = "asdf", str became a primitive type and the Object instance that was originally created is now gone, and you can't add properties to primitives.
In the second, it didn't output undefined like you said, I tested it in Firebug and everything worked correctly.
EDIT 3:
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
This is taken from MDN Documentation, when you use string like that var p = String(3) it becomes a conversion function and not a constructor and it returns a primitive string as you can see from the quote above.
Regarding your second comment, I didn't understand how my comment has been defied, because if you try to console.log(p.pr) you'll get undefined which proves p is a primitive type and not an object.
If an array is just an object in the same way a string or a number is an object,
An array is different than strings, numbers, booleans, null and undefined. An array IS an object, while the others in the list are primitive values. You can add properties to the array just like you would with any other object, anything different being just what makes arrays special (the length property you mentioned for example). You cannot add properties or call methods on primitive values.
In this previous answer i talked about the use of Object wrappers over primitive values. Feel free to read it to see more about Object wrappers. The following will be a very short example:
console.log('TEST'.toLowerCase()) // 'test'
While it may seem that the toLowerCase method is called on the string 'TEST', in fact the string is converted automatically to a String object and the toLowerCase method is called on the String object.
Each time a property of the string, number or boolean is called, a new Object wrapper of the apropriate type is created to get or set that value (setting properties might be optimized away entirely by the browser, i am not sure about that).
As per your example:
var num = 1; // primitive value
num.prop_1 = "a string"; // num is converted to a Number, the prop_1 property is set on the Object which is discarded immediately afterwards
console.log(num); //1 // primitive value
console.log(num.prp); // num is converted to a Number, which doesn't have the prp property
My example:
Number.prototype.myProp = "works!";
String.prototype.myFunc = function() { return 'Test ' + this.valueOf() };
Boolean.prototype.myTest = "Done";
console.log(true.myTest); // 'Done'
console.log('really works!'.myFunc()); // 'Test really works!'
var x = 3;
console.log(x.myProp.myFunc()); // 'Test works!'
console.log(3['myProp']); // 'works!'
On the other hand:
console.log(3.myProp); // SyntaxError: Unexpected token ILLEGAL
The number isn't necessarily treated differently, that syntax just confuses the parser. The following example should work:
console.log(3.0.myProp); // 'works!'
I don't understand why Mozilla calls this an Array 'Literal' when it's defined using the VARIABLE keyword and it can be completely changed...
var coffees = ["French Roast", "Colombian", "Kona"];
Can anyone explain this to me?
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Object_literals
You are confusing literal and constant.
A constant doesn't change, but a literal just means you are explicitly setting the array values as a whole.
In other words, you are defining what you literally want the array value to be. The literal itself (on the right side) is constant, but you are assigning it to a variable. In the same way you could assign the value of a constant to a variable.
There are literals for pretty much every data type.
var myNumber = 42; // Number literal
var myString = "Thanks for all the fish"; // String literal
var myObject = { dolphins: 1, humans: 2 }; // Object literal
It is a literal because you use the square brackets var arr = []; to initialize the array as opposed to using var arr = new Array();
It's the same way {} is a literal for objects
A literal is an opposition to a constructor and is simply a convenient language construct.
If you google "literals vs constructors" you will find quite a few pages regarding the subject :)
You can also read more on js literals here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Literals
The written, literal value ["French Roast", "Colombian", "Kona"] actually can't be changed -- it's an array with those exact three strings, and nothing else. Once the literal is stored in a variable, the value of the variable can change, so the variable is non-literal.
You can even change the value of the structure represented by the literal on the fly, e.g., [1,2,3].push(4), but even so, the written value of [1,2,3] is a literal that refers to an array with those three elements.
It's much like using numeric literals, e.g.,in a = 1 + 2 the expressions 1 and 2 are unchangeable literals, but they can be combined to produce new results (and obviously the value of a can change).
The term "literal" just means "here is the array, right here, the whole thing". A non-literal way of creating the same array could be:
var coffees = new Array();
coffees.push("French Roast");
coffees.push("Colombian");
coffees.push("Kona");
The main reason the term array literal gets brought up is that creating an array using the [] literal or the Array() constructor is not guaranteed to produced the same results all of the time. This is because the Array() constructor could be altered or even replaced by a script. Consider this example:
Array = function() {
var n = 0;
for (var i=0, l=arguments.length; i<l; i++) {
n += arguments[i];
}
return n;
}
var myArray = Array(1,2,3); // myArray type is number, value 6, probably not what you'd want
Versus
var myArray = [1,2,3]; // myArray type is object, value [1,2,3], probably what you'd want
So in addition to the literal syntax being more concise, it is also 100% predicable.
Convert this:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}
To this:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"} that is... {id: quantity}
I found an answer that almost does what I need: Searching for an Object inside the JSON. But that answer doesn't help me because it's only at the first level (one json object). My problem is at the second level (json object within a json object). Thanks in advance!
It helps if you don't think of JSON objects as JSON objects. Once you run a JSON string through JSON.parse, it is a native JavaScript object.
In JavaScript, there are two ways to access objects.
Dot Notation
The dot notation goes like this
myObject.name
See the dot? You can use that to access any object property (which indeed may be another object in javascript, as long as it has a valid dot notation name). You can't use characters like -, ., and the space character.
Bracket Notation (may be another name)
myObject["variableName"]
Like dot notation but allows some other characters, like - and the space character.. Does exactly the same thing.
Using these notations is useful because we can access nested properties.
myObj.foo.bar.baz()
Now let's get to your JSON object...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
You might want to brush up on the JSON format yourself, but in your example, here's a few clues...
{ Means the start of an object. (Keep in mind your entire JSON string is an object itself.)
} Means the end of an object.
"variable" (with quotes! important in JSON, but not when accessing/declaring javascript objects) assigns a property to your object.
: Is the assignment operator in both JSON and JavaScript objects.
Anything to the right of the : is the value you are assigning to the property on the left.
, Means you are starting a new property within an object.
You probably know that [] with , commas inside means an array.
When we run your string through JSON.parse(string), we'll get an object that looks like this...
var myResponse = JSON.parse(response);
You can now use it as a native JavaScript object. What you're looking for is a nested property within "items".
var items = myResponse.items; //alternatively you could just use myResponse.items
Since items is an array of objects, we'll need to iterate through it in order to convert the existing object into a new object.
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.
Result is now an object that looks like:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}
You can access the properties using bracket notation.
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
You can try with:
var obj = {
"items":[
{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}
],
"country":"JUS",
"region":"A",
"timeout":"FILLER"
};
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
quantities will then be the object {"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}. forEach is a native method of array objects in JavaScript that lets you iterate through their elements. You may want to put that piece of code inside a function:
function getQuantities(obj) {
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
return quantities;
}
You need to do the following:
var newJSON = {};
for (var i = 0; i < oldJSON.items.length; i++) {
newJSON[oldJSON.items[i].id] = oldJSON.items[i].quantity;
}
In my script there is a need to create a hash table, and I searched in google for this. Most of the folks are recommending JavaScript object for this purpose. The The problem is some of the keys in the hash table have a "." in them. I am able to create these keys easily with the associative arrays.
I don't understand why associative arrays are bad. The first thing that is mentioned on the sites that I looked at is the length property.
I am coming from the Perl background, where I used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair. If these are my common uses, can I safely use an associative array?
In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:
var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';
alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'
If you're using them already and they work, you're safe.
In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:
var obj = {"my.key": "myValue"};
vs.
var obj = [];
obj["my.key"] = "myValue";
Therefore never use the array object for this, but just the regular object.
Some functionality:
var obj = {}; // Initialized empty object
Delete a key-value pair:
delete obj[key];
Check if a key exists:
key in obj;
Get the key value:
obj[key];
Add a key-value pair:
obj[key] = value;
Because there is no such thing as built-in associative arrays in JavaScript. That's why it's bad.
In fact, when you use something like:
theArray["a"] = "Hello, World!";
It simply creates a property called "a" and set its value to "Hello, World!". This is why the length is always 0, and why the output of alert(theArray) is empty.
Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript. Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype.
So, a Perl hash and an ECMAScript object behave similarly. You might not know that you can access object properties not only via a dot, but also with brackets and strings, like
var myObj = { foo: 42 };
myObj.foo; // 42
myObj['foo']; // 42
Knowing that, you can also use keys with .
var myObj = { };
myObj['hello.foo.world'] = 42;
Of course, you can access that key only with the bracket notation.
You can use . in key names on JavaScript objects (AKA associative arrays) if you'd like; they're accepted without issue. The minor drawback is you can't use shortcut notations with the dotted keys, e.g.
var x = {};
x['hello'] = 'there';
alert(x.hello);
is perfectly acceptable and will pop up an alert with 'there' in it. But if you use a dotted name:
var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);
will fail, as JavaScript will look for an attribute named this in the x object, which does not exist. There is only the this.is attribute.
There isn't an associative array. It's just an object.
foo.bar; // Equivalent to...
foo["bar"]; // Looks like associative array.
For the sake of convenience of using data, there should be no difference between an object and an array. You can think of it as an object or you can think of it as an associative array. At the end, you can just think of everything as data.
For PHP, [ ] accepts 0, 1, or more items(array), and it is called an associative array. It is JSON in PHP's coat:
$data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];
For JavaScript, { } accepts 0, 1, or more items(array), and it is called an object. This data format is JSON:
data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};
I just call them data. The simplest way to describe data is JSON, or its variants.