This question already has answers here:
Map vs Object in JavaScript
(15 answers)
Closed 2 years ago.
let m = new Map();
let obj = {};
let keyString = 'a string';
let keyObj = {};
let keyFunc = function() {};
obj[keyObj] = 'object inside object as keys!';
obj[keyFunc] = function() {}
m.set(keyObj, 'object');
m.set(keyFunc, 'function');
console.log(typeof obj[keyObj]); // type = string
console.log(typeof obj[keyFunc]); // type = function
console.log(typeof m.get(keyObj)); // type = string
console.log(typeof m.get(keyFunc)); // type = string
console.log(m.get(keyObj)) // object
console.log(m.get(keyFunc)) // function
Then what is difference between map and object?
map also converts the keys type to string.
Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.
Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations.
Few basic differences are as follows:
In Object, the data-type of the key-field is restricted to integer,
strings, and symbols. Whereas in Map, the key-field can be of any
data-type (integer, an array, even an object!)
In the Map, the original order of elements is preserved. This is not
true in case of objects.
The Map is an instance of an object but the vice-versa is not true.
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 months ago.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
Second try:
var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?
The correct way is:
const A = 0;
const LOOKUP = {};
LOOKUP[A] = 'A';
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
const LOOKUP = { A : "A"};
The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"])
If you want the key to be a computed value, then you need to use square brackets:
const LOOKUP = { [A]: "A" };
That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])
Looks like you are searching for some enums (typescript):
enum ETest {
A = 1
};
console.log(ETest['A']); // 1
console.log(ETest[1]); // A
Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined.
You should try it as
console.log(LOOKUP["A"])
This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string).
console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
This question already has answers here:
JavaScript set object key by variable
(8 answers)
Closed 2 years ago.
I am trying to get a static Java-like map object working in Javascript. I am not a javascript expert, but am wondering if this is possible. What I am trying to do is the following:
I am defining
const MY_CONST_1 = 'Constant 1 value';
const MY_CONST_2 = 'Constant 2 value';
and a "map-like" object like this:
const CONST_AMOUNT_MAP = {
MY_CONST_1: 30,
MY_CONST_2: 22
}
Then, in a function I define:
function getAmount(constValue) {
return CONST_AMOUNT_MAP[constValue];
}
My expectation would be that the above function when called with
getAmount('Constant 1 value')
returned the number "30". However,
CONST_AMOUNT_MAP[constValue];
returns "undefined". Only
CONST_AMOUNT_MAP[MY_CONST_1]
returns the correct amount.
Is it possible to define an Object such as CONST_AMOUNT_MAP that allows to lookup entries based on pre-defined const variables rather than based on the actual value of the consts?
Thank you
When you define an object literal, the key names are given literally - they're not evaluated. In other words:
const CONST_AMOUNT_MAP = {
MY_CONST_1: 30,
MY_CONST_2: 22
}
...makes an object with a key named MY_CONST_1, not the value of any variable you've defined with the name MY_CONST_1.
You can achieve what you're after by instead declaring your keys wrapped in [], which will force the enclosed to be evaluated.
const CONST_AMOUNT_MAP = {
[MY_CONST_1]: 30,
[MY_CONST_2]: 22
}
Or
const CONST_AMOUNT_MAP = {};
CONST_AMOUNT_MAP[MY_CONST_1] = 30;
CONST_AMOUNT_MAP[MY_CONST_2] = 22;
Note that the keys, however you add them, must be strings or symbols. Since you mention 'map', be aware that there are true maps in JS, in which the keys can be of any data type.
This question already has answers here:
JavaScript hashmap equivalent
(17 answers)
Closed 7 years ago.
I want to create a map object in javascript. I came to the following idea:
var a = new Array();
a["key1"] = "value1";
a["key2"] = "value2";
but then how I can find if a particular key exists or not?
Don't use an array if you want named keys, use a plain object.
var a = {};
a["key1"] = "value1";
a["key2"] = "value2";
Then:
if ("key1" in a) {
// something
} else {
// something else
}
A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.
Maps do not support the [subscript] notation used by Objects. That syntax implicitly casts the subscript value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key), .set(key, value) and .has(key).
var m = new Map();
var key1 = 'key1';
var key2 = {};
var key3 = {};
m.set(key1, 'value1');
m.set(key2, 'value2');
console.assert(m.has(key2), "m should contain key2.");
console.assert(!m.has(key3), "m should not contain key3.");
Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2 and key3 because their string representations would be the same:
var o = new Object();
var key1 = 'key1';
var key2 = {};
var key3 = {};
o[key1] = 'value1';
o[key2] = 'value2';
console.assert(o.hasOwnProperty(key2), "o should contain key2.");
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
Related
MDN Documentation: Map, Symbol, Set, WeakMap, WeakSet
You want to create an Object, not an Array.
Like so,
var Map = {};
Map['key1'] = 'value1';
Map['key2'] = 'value2';
You can check if the key exists in multiple ways:
Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...
Use the in operator: e.g. "key1" in a.
if( a['desiredKey'] !== undefined )
{
// it exists
}
This question already has answers here:
What's the point of new String("x") in JavaScript?
(9 answers)
Closed 7 years ago.
I'm very confused about what the wrapper objects for primitives. For example, a string primitive and a string created with the string wrapper object.
var a = "aaaa";
var b = new String("bbbb");
console.log(a.toUpperCase()); // AAAA
console.log(b.toUpperCase()); // BBBB
console.log(typeof a); // string
console.log(typeof b); // object
Both give access to String.prototype methods, and seem to act just like a string literal. But one is not a string, it's an object. What is the practical difference between a and b? Why would I create a string using new String()?
A primitive string is not an object. An object string is an object.
Basically, that means:
Object strings are compared by reference, not by the string they contain
"aaa" === "aaa"; // true
new String("aaa") === new String("aaa"); // false
Object strings can store properties.
function addProperty(o) {
o.foo = 'bar'; // Set a property
return o.foo; // Retrieve the value
}
addProperty("aaa"); // undefined
addProperty(new String("aaa")); // "bar"
I need to store an object in localStorage - and I know that in order to do so, I have to convert the object into a string. All cool.
My problem is in actually creating the object in the first place: I have two values in sessionStorage that need to be added to the object which is then passed into localStorage. However, when I try to create the object, one value is being stored as the variable name rather than its (numeric) value. Any idea whats going on here?
var siteName = sessionStorage['1'];
var siteID = (+sessionStorage['2']);
var temp = {siteID:siteName};
alert(typeof siteID);
alert(JSON.stringify(temp));
The first alert confirms that siteID is indeed a number type, but the second alert shows that the variable name (siteID) is stored rather than its numeric value.
This line:
var temp = {siteID:siteName};
...creates an object containing a property called siteId with the value taken from the siteName variable.
If you want the property name to be taken from the siteID variable instead:
var temp = {};
temp[siteID] = siteName;
Or in ES2015 (aka "ES6") you could use the new computed property name syntax:
// ES2015+ only!
var temp = {[siteId]: siteName};
In JavaScript, you can access/create properties on objects in two different but equal ways: Using dotted notation with a literal property name:
obj.foo = "bar"; // Creates a `foo` property on `obj` with the value `"bar"`
...or using bracketed notation and a string:
obj["foo"] = "bar"; // Does the same thing
The keys in object initializers like your var temp = {siteID:siteName}; are always used literally (although they can optionally be in quotes); there's no way with an object initializer to have a key taken from a variable instead. So you have to do it as a two-step process, first create the object, then set the property.
So, if you do
temp[siteID] = siteName;
...the number in siteID will be converted to a string and will become the property name, with the value of siteName being the value.
var temp = {};
var key = 1;
temp[key] = "value";
console.log(temp[1]); // "value"
console.log(temp["1"]); // "value"
(Property names are always strings in JavaScript [for now].)
Change it to this.
var temp = {};
temp[siteName] = siteID;
Or if the typeof test was meant to show the property name, you'd reverse them.
var temp = {};
temp[siteID] = siteName;
But be aware that siteID is considered a String from that point forward.