Search for multiples Keys on new Map() - javascript

Normally what we do is like
const hash = new Map()
hash.set(key,value)
And when we want to retrieve the information just
hash.get(specificKey)
One of the benefits that Map has is that we can put whatever we want as key or value.
I'm trying to set a multiple value of keys on the "key" part of the map, that's not the problem is later when I want to get the information
Example:
[
{name:"Pedro",email:"test1#gmail.com"},
{name:"Anibal",email:"test2#gmail.com"},
]
I want to create the key of the map with both properties of the object (name, email), and the value is ALL the iterated register so...
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set([name, email], register)
}
The problem is when I want to GET the register by one of the properties on the key.
We know that the key could be ["Pedro","test1#gmail.com]
How I can get the value of the Map if the key I want to get could be just "Pedro" or just "test1#gmail.com"
It is possible? :(
Thank you
___________________-
Answer to #Kevin Kinney
Thank you for answering. The idea that I want to do is to avoid this;
I dont want to have a find inside the map. Any different approach?

One idea, if you know only a few of the properties would be used as keys
const hash = new Map()
for (register of registers) {
const { name, email } = register
hash.set(name, register)
hash.set(email, register)
}
This will allow fast access to the value in the map, but increases the memory usage.
Otherwise I don't think a hashmap is the right idea if you don't know what key you will be expecting to use.

No, this is not possible
You want access in a non-standard way so what you can do is create two mappings for each value. One goes from pedro and one goes from test1#gmail.com
Then when you need to retrieve the value you can get it by either

Related

MongoDB map a JSON response into a string

var db = mongoose.connection;
const FoundWarning = db.collection('warning').find({UserID: Warned.user.id, guildID: message.guild.id}).toArray(function(err, results) {
console.log(results);
})
I was trying to find more than one collection using MongoDB,
I don't quite know how to map it and turn it into a String as there are multiple responses and not just one JSON document to use so I would have to map through them,
Can someone explain how I can turn this Data to chunks that I can use like a string, an object or an array?
I suppose I have to parse it and map it first, correct me if I'm wrong
But I don't think I know how to do that
Here is the photo of the current result that I have
I wanted to (for example) get the "Reason" part of it in a string alone and send each "Reason" along side with the "UserName" and send it as a message on discord using discord.js so like loop through them for example
Edit: i forgot to mention that "Warned" is
let Warned = message.mentions.members.first();
Sorry if I'm not good at explaining, I would appreciate edits if you understand what's the issue that I'm facing
Like I said here
You can simply access the Reason property of an object. What you are facing is an array of objects and each object inside the array contains a Reason property. You can either access one object, for example, results[0] and then access the Reason property like this results[0].Reason or you can store all the reasons inside an array like this:
const reasons = results.map(result => result.Reason);

How to increment a map value in a Firestore array

I have a firestore firebase database , in which I have a collection users
there is an array in the collection and in the array there is a map
in map there is a field qty.. I want to increment that qty value..
using increment doesnt help as the qty is inside a array index
db.collection("users").doc(checkId).update({
myCart: firebase.firestore.FieldValue.arrayUnion({
qty: firebase.firestore.FieldValue.increment(1),
}),
this is the error Output =>
Uncaught (in promise) FirebaseError: Function FieldValue.arrayUnion() called with invalid data. FieldValue.increment() can only be used with update() and set()
My answer below won't work, given that the qty is in an array. The only way to update an item in an array is to read the entire document, update the item in the array, and then write the entire array with the updated item back to the document.
An alternative would be to use a map instead of an array, and then update the qty using the approach outlined in my (old, and non-working) answer below 👇
You need to specify the full path to the field you're trying to update. So I think in your case, that'll be:
db.collection("users").doc(checkId).update({
"myCart.0.qty": firebase.firestore.FieldValue.increment(1)
}),
The field you want to update is embedded in an array. In this case, you can't use FieldValue.increment(), since it's not possible to call out an array element as a named field value.
What you'll have to do instead is read the entire document, modify the field in memory to contain what you want, and update the field back into the document. Also consider using a transaction for this if you need to update to be atomic.
(If the field wasn't part of an array, you could use FieldValue.increment().)
As of today (29-04-2020)... this is tested by me.
Suppose my data structure is like this:
collection: Users
Any document: say jdfhjksdhfw
It has a map like below
map name: UserPageVisits
map fields: field1,field2,field3 etc
Now we can increment the number field in the map like below:
mapname.field1 etc...
That is use the dot operator to access the fields inside the map just like you would do to an object of javascript.
JAVA Code (Android), update the field using transactions so they can complete atomically.
transaction.update(<documentreference object>,"UserPageVisits.field1",FieldValue.increment(1));
I have just pushed a version of my app which uses this concept and it's working.
Kudos !!
My Best Regards
Previous answers helped me as well, but dont forget about the "merge" property!!! Otherwise it will overwrite your entire array, losing other fields.
var myIndex = 0;
const userRef = db.collection('users').doc(checkId);
return userRef.update({
'myCart.${myIndex}.qty': admin.firestore.FieldValue.increment(1)
}, {
merge: true
});

Correct way to model a collection of items in Firebase

In the docs I see a lot of examples using index values as a part of the key name for a particular item --- but I don't understand how this is a consistent way to model your data.
For example let's say I have a list of articles:
https://gigablox.firebaseio.com/articles/
article1
article2
article3
When I'm ready to add article4 I know I can use:
var length = Object.keys($scope.articles).length;
And using AngularFire 0.5.0 I can save it with:
var name = 'article' + length + 1;
$scope.articles[name] = $scope.article;
$scope.articles.$save(name);
But what happens if I:
$scope.articles.$remove('article2');
And add another record using the same approach? We're likely to create duplicate key names.
To add a little complexity, let's add a single relationship and say that each article has comments.
What is the correct way to model this data in a Firebase collection?
Please use $add and let Firebase automatically generate chronologically ordered lists for you.
var ref = new Firebase("https://gigablox.firebaseio.com/articles/");
$scope.articles = $firebase(ref);
$scope.addArticle = function() {
$scope.articles.$add($scope.article);
}
$scope.removeArticle = function(id) {
$scope.articles.$remove(id);
}
Firebase automatically creates key names when you call $add. You can iterate over the key names using ng-repeat:
<div ng-repeat="(key, article) in articles">
<div ng-model="article"><a ng-click="removeArticle(key)">Remove</a></div>
</div>
EDIT: You should follow the suggestion from #Anant if you want an array-based collection.
However, for this specific scenario as outlined by #Dan Kanze, if you want to pull the key out of the URL (as would be done for a content management system, etc), you should generate your own keys unique to the content. For example, if you know that article names need to be unique, create a slug function that will:
Lowercase the article name
Replace spaces with underscores
etc..
If the article name changes, you would not delete the old entry. Instead, create a new entry in Firebase and use the old key to point to the new location for 301 redirects, etc.

Deep copying objects in angular?

I wonder if there is away to avoid copying references to objects when you need to create a simple object which has an array of embedded objects.The situation is as follow: I have server which accepts a JSON and applies some logic then stores the object in DB. lets say my form is for saving teams in DB. The server accepts team as json. the team has an array of TeamMember objects, my form has a simple field to enter team member info and add it to team teamMembers array. Now here is the problem, when I add a team member to array list and want to add another team member when I type into the field the added member is changed also !. I know the reason
$scope.addTeamMember=function(teamMember){
$scope.team.teamMembers.push(teamMember);
}
and it is because I put same reference into the teamMembers array so I have same object added several times.
to avoid this I should create a new team member object, copy all teamMember properties and and add it the array.
$scope.addTeamMember=function(teamMember){
var newTeamMember; /*<--- copy teamMember */
$scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/
}
Your question says you want to "avoid deep copy", but I'm not sure that's accurate. It sounds like you just want to use angular.copy, because you need to create a copy of the team member and add that to the array:
$scope.addTeamMember = function(teamMember) {
var newTeamMember = angular.copy(teamMember);
$scope.team.teamMembers.push(newTeamMember);
};
This is the best documentation available
https://docs.angularjs.org/api/ng/function/angular.copy
there is a live example as well on the page which is self illustrative.
I personally use this:
function copyObjToObj(source, destination) {
if(!angular.equals(source,destination)){
if (!!destination)
angular.copy(source, destination);
else
destination = angular.copy(source);
}
return destination;
}
var destination = copyObjToObj(sourceObj, destination);

Capturing form data: variables or array?

I have a form with about 20 input fields. I capture values of these fields, then do some calculations and output several values.
Is there a preferred/recommended way of capturing form data? Currently I store every form field into a separate variable. I was wondering if storing it to an array would be a better and more effective approach.
I'm quite new to Javascript and programming in general, trying to learn the best practices.
My best practice on this depends on what I have to do with the data. If I do not need to loop through it, or send it to another page/service, then there's nothing wrong with individual scoped-variables.
If I need to loop at all, I commonly use an array or object to loop through.
If I have to pass it to another page/service, I make one object variable to encapsulate the rest of them, so I can "stringify" it to JSON and parse back to an object on the other end.
Just my opinion,
Pete
You might consider the third approach - just use the data from the form without storing it anywhere.
First check the correctness, once it is considered correct just use what you have.
You should always assign the attribute "name=..." to an input element, so you can use something like:
var form = document.forms['form'];
var email = form['email'];
email = do something
if you use javascript... if you use jquery it's simple $('input[name="email"]') = do something
I prefer this way because you can call variables by name, not by number, for example "form[0] that corresponds to input[name="email"]".
Use the associative properties of arrays in JavaScript to get the benefits of unique field names and OOP:
var formModel = new Array();
formModel['myField'] = getMyFieldValue(); // make 'myField' index to any object
Then you can do things like:
formModel['myField'] // get the value
formModel.length; // number of fields added
for (entry in formModel) { /* loop thru entries */ }
formModel.sort([compareFunction]) // custom sort
formModel = []; // clear the model
Convert array to JSON
Any of these ArrayMDN conveniences.
Just one approach, but arrays in JS are extremely versatile and IMO underused objects in JS.

Categories

Resources