简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM