Implement "like" HashMap in js with <string, object> - javascript

I develop an app with react and node js.
I have a JSON file that stores all user objects with some properties (first name, last name, email, ... )
I want to implement "like" hashmap with key, value.
the key is a string for the email and value will be all the user object
like (in java):
HashMap< string, User >
I want this to access fast for a user object, search by email (the key) on server-side (NodeJS)
What is a good way to implement something like this?
Thanks!

What about a simple object in Javascript?
All objects in Javascript can be accessed by the Array-like convention.
For example, you can create an object like this:
const Users = {}
Users['admin#admin.com']=userObject;
Users['test#test.com']=user2Object;
ect..

If you are going to work with modern browser/node versions, consider using a Map
Example from the link above:
let myMap = new Map()
let keyString = 'a string'
let keyObj = {}
let keyFunc = function() {}
// setting the values
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')
myMap.size // 3
// getting the values
myMap.get(keyString) // "value associated with 'a string'"
myMap.get(keyObj) // "value associated with keyObj"
myMap.get(keyFunc) // "value associated with keyFunc"
myMap.get('a string') // "value associated with 'a string'"
// because keyString === 'a string'
myMap.get({}) // undefined, because keyObj !== {}
myMap.get(function() {}) // undefined, because keyFunc !== function () {}

Related

how to turn a string into a variable

Im trying to use a command for a chat program and i want to edit a variable with a command like !editvar variablehere value
so if it variablehere = '123' i want to turn '123' into just 123 or something like 'hello' into hello, in simple words im trying to make a string from a chat message into a variable name
ive tried parsing and string.raw and none worked
if(message.startsWith('keyeditvar')) {
console.log(message)
var bananasplit = message.split(' ');
var bananasplitted = json.parse(bananasplit)
console.log(bananasplitted[0].keyeditvar)
var variable = bananasplit[1]
console.log(variable)
var value = bananasplit[2]
console.log(value)
var variable2 = String.raw(variable)
console.log(variable2)
var value2 = String.raw(value)
console.log(value2)
}
i expected it to work ig
im trying to turn a string into a variable name
In Javascript, you don't usually dynamically define new variables with custom names in the current scope. While you can do it at the global scope, you cannot easily do it in the function or block scope without using tools that are generally not recommended (like eval()).
Instead, you use an object and you create properties on that object. You can use either a regular object and regular properties or you can use a Map object with some additional features.
For a regular object, you can do thing like this:
// define base object
let base = {};
// define two variables that contain variable name and value
let someName = "greeting";
let someValue = "hello";
// store those as a property on our base object
base[someName] = someValue;
console.log(base); // {greeting: "hello"}
Then, you can change the value:
someValue = "goodbye";
base[someName] = someValue;
console.log(base); // {greeting: "goodbye"}
Or, you can add another one:
let someOtherName = "salutation";
let someOtherValue = "Dear Mr. Green";
base[someOtherName] = someOtherValue;
console.log(base); // {greeting: "goodbye", salutation: "Dear Mr. Green"}
console.log(base.greeting) // "goodbye"
console.log(base[someName]); // "goodbye"
console.log(base.salutation) // "Dear Mr. Green"
console.log(Object.keys(base)) // ["greeting", "salutation"]
You can think of the Javascript object as a set of key/value pairs. The "key" is the property name and the value is the value. You can get an array of the keys with:
Object.keys(obj)
You set a key/value pair with:
obj[key] = value;
You get the value for a key with:
console.log(obj[key]);
You remove a key/value pair with:
delete obj[key]
With a plain Javascript object like this, the keys must all be strings (or easily converted to a string).
If you have non-string keys, you can use a Map object as it will take any object or primitive value as a key, but it uses get() and set() methods to set and get key/values rather than the assignment scheme of a plain object.
Please, next time put a clean code...
To convert a string to a number. You can use the function : Number(object)
So for example :
Number('123')
will return 123.
If the object value is not a correct number, it will return NaN.
So for example :
Number('hello')
will return NaN.

Using object as ES2015 map key

I've been trying to get a hold of ES2015 map concept and one thing I don't understand is the following:
var mapRawObj = new Map();
var rawObj = {j:"I like penguin"};
mapRawObj.set(rawObj,true);
console.log(mapRawObj.get(rawObj)); //this outputs true
mapRawObj.set({j:"I like polar bear"},true);
console.log(mapRawObj.get({j:"I like polar bear"})); //this outputs undefined
The first one works, the second one doesn't, and I don't understand why?
I thought when you register object as key, it's the object itself, not the object's name. That's why in the below example when you re-assign the key object, it fails as key?
var obj = { a:"hello ", b:"world "};
var mapObj = new Map();
mapObj.set(obj,true);
obj = {d:34}; //obj is re-assigned
console.log(mapObj.get(obj)); // outputs undefined
Objects with the same data are not equal in Javascript, ie
{ hello: 'world'} === { hello: 'world'} // false
The first example uses the same object as the key for set and get, so the key is identical:
var obj = { hello: 'world'};
obj === obj // true
But the second example creates a new object for the get(), which is not identical to the key used to set the value in the map. Since it's not identical, the map doesn't have anything set against this new key and returns undefined.
Even though the new key has exactly the same data as the original key, the objects aren't referring to the same data internally.
More on object equality

Replacing a property key name in Javascript

I feel like this will be one of those "oh jeez, how did I even ask this question" questions, but...
// So I create an object:
var o = {};
// I assign a string value to a variable:
var prop1 = "prop_key";
// And I use that variable that resolves to that string as the property name:
o[prop1] = "value1";
// => So far so good, the property key is the right value:
console.log(o); // => Object {prop_key: "value1"}
// Moving on, I am malicious and overwrite the `prop1` variable, replacing the original value to say, another string:
prop1 = "evil_string";
// And just to make sure it worked:
console.log(prop1); // => evil_value:
// AND YET, when I query the object...
console.log(o); // => Object {prop_key: "value1"}
Shouldn't it now output Object{"evil_value": "val1"} since o[prop1] no longer points to that original prop_key value?

Using Javascript object as object key

I am trying to devise a way to use a simple Javascript object (one level deep key value pairs) as a key to another object. I am aware that merely using the object without stringification will result in [Object object] being used as the key; see the following: Using an object as a property key in JavaScript (so this question is not a duplicate).
There is a blog post about it that takes this into account and also accounts for the need to sort by object key since their order is not guaranteed, but the included Javascript code runs over a 100 lines. We are using the underscore.js library since that goes hand in hand with backbone but pure Javascript alternatives will also be of interest.
In ECMAScript 6 you'll be able to use Maps.
var map = new Map();
var keyObj = { a: "b" },
keyFunc = function(){},
keyString = "foobar";
// setting the values
map.set(keyObj, "value associated with keyObj");
map.set(keyFunc, "value associated with keyFunc");
map.set(keyString, "value associated with 'foobar'");
console.log(map.size); // 3
// getting the values
console.log(map.get(keyObj)); // "value associated with keyObj"
console.log(map.get(keyFunc)); // "value associated with keyFunc"
console.log(map.get(keyString)); // "value associated with 'a string'"
console.log(map.get({ a: "b" })); // undefined, because keyObj !== { a: "b" }
console.log(map.get(function(){})); // undefined, because keyFunc !== function(){}
console.log(map.get("foobar")); // "value associated with 'foobar'"
// because keyString === 'foobar'
I wrote a hash table implementation that accepts arbitrary keys but I suspect you'll reject it on the grounds of the relatively large file size.
https://code.google.com/p/jshashtable/
Here is an underscore based solution that relies on first converting the object to key-value pairs.
var myObj = { name: 'john', state: 'ny', age: 12};
var objPairs = _.pairs(myObj);
var sortedPairs = _.reduce(_.keys(myObj).sort(), function(sortedPairs, key) {
var pair = _.find(objPairs, function(kvPair) {return kvPair[0] == key});
sortedPairs.push(pair);
return sortedPairs;
}, []);
console.log(JSON.stringify(sortedPairs)); //stringifying makes suitable as object key
// [["age",12],["name","john"],["state","ny"]]
You could use a pattern like this. This way, your key for an object is this random id that you generate for every object.
var MyObject = function(name) {
this.name = name;
this.id = Math.random().toString(36).slice(2);
}
MyObject.prototype.toString = function() {
return this.id;
}

Javascript empty object

This is an example of code, from a book called JavaScript: The Definitive Guide, 6th Edition, that I do not understand.
He is talking about Objects.
var book ={
topic: "javascript",
fat: true
};
book.topic => "javascript"
book.["fat"] => True
book.author="flanagan"; // creates new property
book.contents= {}; // empty object*
So what I don't understand is the last part. Is he adding in a new property called "contents" that is empty? Because he is calling it an object and it's confusing me.
Yes {} is an empty object in javascript which is being assigned to the contents property of the book object.
Here you can see that we can use functions defined globaly on object such as toString()
Take a look at the way the book variable is defined. It is an Object declaration.
In the last line, we add a property named contents and assign it an object declared exactly the same way as book except that this one has no property and therefore is an empty object : {}
The curly bracket { } notation denotes an object literal.
The fact that there is nothing between them means that a new object reference pointing to a blank object (inheriting from the base object) is stored in the book.contents property.
{} create an empty object. Means now this object can have new property same as defined by book.author="flanagan";
// Both are same
book.contents = new Object();
book.contents = { } ;
In JavaScript you can create an object with {} notation, called object literal and you can add what ever you want to this object in future by dot even a function , in your example in first step:
var book ={topic: "javascript",fat: true};
book object is created with two property topic and fat and then this object is extended with author as String and contents as an inner object, as I said you can use it for creation empty objects (var t={} //example);
and if you use
typeof book.contents // returns "object"
It's creating a new property of the original book object, and setting the value of that property to a new empty object.
He's adding a new property called contents of the object book which itself is an empty object.
Here is a structure of what it would look like when he's made his changes to help you visualise it.
var book = {
topic: "javascript",
fat: true,
author : "flanagan",
contents : {}
};
<script type="text/javascript">
var book ={
topic: "javascript",
fat: true
};
book.topic = "javascript";
book.fat = true;
book.author = "flanagan"; // creates new property
book.contents = {}; // empty object*
//The curly bracket { } denotes here an object.
//will add a property contents and will contain an empty object
alert(book.contents); //it will display [object Object]
book.contents.name = 'Success Stories';
//adding propertis to the object contents
alert(book.contents.name);
/*
you can consider it as object inside object
objectOuter {
property1: value1
property2: value2
property3: objectInner {
property1: value1
property2: value2
}
}
*/
</script>

Categories

Resources