Create map <key,value> on JQuery [duplicate] - javascript

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
}

Related

what is difference between object and map object in Javascript? [duplicate]

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.

Memory efficient way to make an object empty in javascript?

Basically what I want to do is, to use single object everytime after make it empty when my purpose is served.
For array in javascript, I used to write arr.length=0 to make any array empty, instead of pointing it to different memory location. is there any way through which I can empty an object in javascript ?
Scenario is:
var obj = {};
obj["name"]="Aman";
obj["country"]="India";
console.log(obj); // output is { name: 'Aman', country: 'India' }
Can I reused this obj object after removing its content ? if so how ?
The only way I can think of would be to loop over the object and delete each property in turn.
var obj = {};
obj["name"]="Aman";
obj["country"]="India";
for (var prop in obj) {
// Possibly with a hasOwnProperty test, depending on how empty you want it to be
delete obj[prop];
}
console.log(obj);
Obviously, if you aren't dealing with multiple references to the object, you can just overwrite it with a new one.
var obj = {};
obj["name"]="Aman";
obj["country"]="India";
obj = {};
console.log(obj);
for (var member in myObject) {
if ( myObject.hasOwnProperty(member) ) {
delete myObject[member];
}
}
use ECMAScript 6 Map:
var obj = new Map();
obj.set("name", "Aman");
obj.set("country", "India");
obj.clear();

How to convert String to an object type

I'm using emberjs to find stuff but the question is more JS related than Ember.
I have two variables: var type = "stars"; var term = "5"
I have a property called stars in my API.
When I do: App.Response.find({stars: term}); I find results
However, when I do: App.Response.find({type: term}); I don't find results. I want this to be translated to App.Response.find({stars: term}) since type has value "stars"
I am assuming this is because type (with value stars) is not being understood as a hash key?
Exactly - it will not evaluate object keys. If you want to dynamically create that object as {stars:5} you could do:
var obj = {};
obj[type] = term;//Using the array notation will cause JS to evaluate type to "stars" and use that as the key
//obj is now {stars:5}
App.Response.find(obj);
There's no dynamic way to set object keys in an object literal.
You have to do
var conditions = {},
type = "stars",
term = "5";
conditions[type] = term;
App.Response.find(conditions);
If you find yourself using this pattern a lot, you could setup something like
var buildObject = function(key, value) {
var base = {},
base[key] = value;
return base;
};
var type = "stars",
term = "5";
App.Response.find(buildObject(type, term));
// or directly as
App.Response.find(buildObject("stars", "5"));
Lastly, let's make the buildObject helper a little more useful
// accepts [key, value] pairs
var buildObject = function() {
var base = {};
for (var i=0; i<arguments.length; i++) {
base[arguments[i][0]] = arguments[i][1];
};
return base;
};
Now we can pass in multiple pairs
App.Response.find(buildObject(["stars", "5"], ["foo", "bar"]));
// equivalent to
App.Response.find({stars: "5", foo: "bar"});

How to create a simple map using JavaScript/JQuery [duplicate]

This question already has answers here:
JavaScript hashmap equivalent
(17 answers)
Closed 6 years ago.
How can you create the JavaScript/JQuery equivalent of this Java code:
Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times
function Object get(k) {
return map.get(k);
}
Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
function get(k) {
return map[k];
}
//map[myKey1] == get(myKey1);
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
function Map() {
this.keys = new Array();
this.data = new Object();
this.put = function (key, value) {
if (this.data[key] == null) {
this.keys.push(key);
}
this.data[key] = value;
};
this.get = function (key) {
return this.data[key];
};
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
this.each = function (fn) {
if (typeof fn != 'function') {
return;
}
var len = this.keys.length;
for (var i = 0; i < len; i++) {
var k = this.keys[i];
fn(k, this.data[k], i);
}
};
this.entrys = function () {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key: this.keys[i],
value: this.data[i]
};
}
return entrys;
};
this.isEmpty = function () {
return this.keys.length == 0;
};
this.size = function () {
return this.keys.length;
};
}
This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...
The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:
function MyObject(name) {
this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");
var map = {};
map[key1] = 1;
map[key2] = 2;
If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:
> JSON.stringify(map);
{"[object Object]": 2}
This is clearly not a replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.
In the meantime, the best you can do is:
Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1
Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();
var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values

create object using variables for property name [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
Is it at all possible to use variable names in object literal properties for object creation?
Example
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.propertyName); // Prints "value"
console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){
var myObject = { [propertyName] : "Value"};
}
Note browser support is currently negligible.
You can sort of do this:
var myObject = {};
CreateProp("myProperty","MyValue");
function CreateProp(propertyName, propertyValue)
{
myObject[propertyName] = propertyValue;
alert(myObject[propertyName]); // prints "MyValue"
};
I much perfer this syntax myself though:
function jsonObject()
{
};
var myNoteObject = new jsonObject();
function SaveJsonObject()
{
myNoteObject.Control = new jsonObject();
myNoteObject.Control.Field1= "Fred";
myNoteObject.Control.Field2= "Wilma";
myNoteObject.Control.Field3= "Flintstone";
myNoteObject.Control.Id= "1234";
myNoteObject.Other= new jsonObject();
myNoteObject.Other.One="myone";
};
Then you can use the following:
SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);
NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.
function func(prop, val) {
var jsonStr = '{"'+prop+'":'+val+'}';
return JSON.parse(jsonStr);
}
var testa = func("init", 1);
console.log(testa.init);//1
Just keep in mind, JSON property names need to be enclosed in double quotes.

Categories