Ori Bentov
Ori Bentov

Reputation: 37

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

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!

Upvotes: 0

Views: 1358

Answers (2)

Yuri Gor
Yuri Gor

Reputation: 1463

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 () {}

Upvotes: 1

arielb
arielb

Reputation: 390

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['[email protected]']=userObject;
Users['[email protected]']=user2Object;

ect..

Upvotes: 1

Related Questions