In order to send an email to multiple recipients via SendGrid API v3 using a dynamic template, I need to pass an email parameter like:
"to":[
{
"email":"example1#example.com"
},
{ "email": "example2#example.com"
}
],
Obviously I am not wanting to hard code these email addresses s.t. they are dynamic.
I currently generate a list of emails with this code:
// loop through users
var users = group.user;
var emails = users.map(function (obj) {
return obj.email;
});
Which returns eg:
[ 'example1#example.com',
'example2#example.com' ]
How do I return instead the array of hashes:
[
{
"email":"example1#example.com"
},
{ "email": "example2#example.com"
}
]
Maybe what you are trying to say is hashmap, not hashes, if not, I don't understand the question.
To achieve the lists of maps that you mention, your code should be something like:
// loop through users
var users = group.user;
var emails = users.map(function (obj) {
return {email: obj.email};
});
Every item of the list would have email as key, and the email as value.
What is a hash: https://en.wikipedia.org/wiki/Hash_function
What is a hash table: https://en.wikipedia.org/wiki/Hash_table
What is a js object: https://www.w3schools.com/js/js_objects.asp
Related
I want to retrieve an arraylist with all the ids of the users that have a specific email domain (exe: #generatedEmail.com)
This is an example of how the json would look like; basically a Json Array with Json objects.I need to get a list with the ids of the objects that contain #generatedEmail.com in the email field.
[{
"id": "1234-5678-7890-1231",
"email": "blabla#generatedEmail.com",
}, {
"id": "gsdg4-fc32-dsfs-4213",
"email": "another#generatedEmail.com",
},{
"id": "pgo4-ffx2-621s-gju3",
"email": "otheremail#dontdelete.com",
}]
My end purpose is to pass this list of ids as parameters to a DELETE endpoint. I found in the Karate documentation that if I pass the list as a parameter when I call the feature file where I describe the Delete steps, it will act as a for each and fire the request for each id in the list.
Thank you in advance!
I tried with different Js functions, but I suck at it and had no success. The below returns to me the emails, but I don't know how to get their related ids. I thought to do the same thing with the ids then match them based on index, but I feel that I would be overengineering it and there must be something simpler and smarter.
* def emails = karate.jsonPath(usersList.response,"$..email")
* def condition = function(x){return x.includes('generatedEmail.com')}
I also tried this with the belief that I would get an array of the objects that I want from which I can later extract only the ids in another arraylist:
* def ids = []
* def fun = function(i){if(i.includes('generatedEmail')) {ids.add(i)}}
* karate.repeat(usersList.response, fun)
Then I also tried this but to no avail
* eval karate.forEach(usersList.response, function(user){if(user.email.includes('generatedEmail')) { ids.add(user.id)} })
Please forgive my lack of knowledge and ignorance :D
Just for your reference, you can do this in one-line if you are familiar with JS. It is elegant and kind of fun:
* def response =
"""
[
{
id: '1234-5678-7890-1231',
email: 'blabla#generatedEmail.com'
},
{
id: 'gsdg4-fc32-dsfs-4213',
email: 'another#generatedEmail.com'
},
{
id: 'pgo4-ffx2-621s-gju3',
email: 'otheremail#dontdelete.com'
}
]
"""
* def filtered = response.filter(x => x.email.includes('#generatedEmail.com')).map(x => x.id)
* match filtered == ['1234-5678-7890-1231', 'gsdg4-fc32-dsfs-4213']
I figured out the answer to my question.
The function filters and returns all json objects that contain the 'generatedEmail.com' pattern in their email fields.
Then I use the returned list and deepscan it to only retrieve the id fields in another list.
* def condition = function(x){return x.email.includes('generatedEmail.com')}
* def filtered = karate.filter(response, condition)
* def ids = karate.jsonPath(filtered,"$..id")
I have an apex list which returns a result of SOQL.
List<Account> List1=[select Name, Phone from Account where Name=:actName];
This method is being called from a JS file of my Lightning Web Component and the result is being saved in an array.
#wire(getAccounts,{actName:'$accountName'})
retrieveAccouts({error,data}){
if(data){
this.accountList = data;
}
else if(error){
}
}
I have a row of this account selected on UI and the Name of selected account. I want to search other details of that account in this array (accountList). How do I achieve this?
I tried to use find() method on the array but did not work. What else can be used? What condition should be used if I use filter() on this array?
filter takes a function that should return true (truthy) or false (falsey) but the conditions are whatever's needed.
If the condition was we needed to filter Account Names containing 'Bob' we could:
this.accountList = [{Name: 'Alice'}, {Name: 'Bob1'}, {Name: 'Bob2'}]
const bobs = this.accountList.filter(acc => acc.Name.includes('Bob'))
console.log(bobs) // [{ Name: "Bob1" }, { Name: "Bob2" }]
A gotcha that came to mind is case sensitivity and that the data from SOQL is always as the Field API Name / Developer Name is. Above I use Name like Account.Name but other fields like AccountNumber can be camel case and custom fields need the __c etc (Custom_Field__c). You can turn on debugging in Salesforce or you can console out the data to see exact field names by stringifying, parsing then logging out like:
console.log( JSON.parse( JSON.stringify( { list: this.accountList } )))
find is very similar but instead of returning an Array, it returns the first Object that's true/truthy:
this.accountList = [{Name: 'Alice'}, {Name: 'Bob1'}, {Name: 'Bob2'}]
const bob = this.accountList.find(acc => acc.Name.includes('Bob'))
console.log(bob) // { Name: "Bob1" }
I have a users collection and Companies collection. Right now the output looks like this:
"_id":"5ce543a5390d87567f523153",
"updatedAt":"2019-10-18T15:01:53.812Z",
"createdAt":"2019-05-22T12:42:13.046Z",
"associatedCompany":{
"_id":"5ce543a4390d87567f523148",
"companyName":"Company Two"},
"accountStatus":1,
"roleInfo":{"roleType":1},
"role":2,
"personalInfo":{
"fullName":"SomeName",
"firstName":"Name",
"lastName":"Last",
"email":"email#email.com",
"phone":{"countryCode":"SE","number":"9876543210"}}}
Where company field is populated from Company collection.
Is there a way to display just a company name right away with firstName and lastName field without "personalInfo" field so the output will look like:
{"data":[{
"_id":"5ce543a5390d87567f523153",
"updatedAt":"2019-10-18T15:01:53.812Z",
"createdAt":"2019-05-22T12:42:13.046Z",
"companyName":"Company Two",
"accountStatus":1,
"roleInfo":{"roleType":1},
"role":2,
"firstName":"Name",
"lastName":"Last",
"email":"email#email.com"
Query I am using
const listUsers = (skip, limit = 10) => {
let config = {
populate: {
'path': 'associatedCompany',
'select': 'companyName'
},
limit: Number(limit),
skip: Number(skip),
};
I have tried to do it with aggregation and lookup but without success.
Thanks is advance.
Use projection to filter the fields that you want to be displayed in your output.
Refer:
mongoDB projection
Using JavaScript I am pulling names out of webpage and stringing them together somehow (probably going with an array). Once I gather all the names together I need to make another string that gives all the email addresses of the names. The email addresses are not on the webpage so I will have to list every possible thisName=thisEmail in my script somehow. I was about to approach this with making a bazillion if statements but I thought there has to be a more efficient way. Any suggestions?
var x = getElementById("names");
var name = x.InnerHTML;
var email;
if (name == 'Steve'){ email == 'steve462#gmail.com'; }
if (name == 'Bob'){ email == 'duckhunter89#gmail.com'; }
....
A switch statement, as your code is only if-elses :-)
No, honestly. The best thing would be if you'd find a simple algorithm to create an email address from any given name, like
function mail(name) {
return name.toLowerCase() + "#gmail.com";
}
var email = mail("Bob") // example usage
If they differ to much, you might use an object as a key-value-map:
var mails = {
"Steve": "steve#gmail.com",
"Bob": "bob1#freemail.org",
...
}
var email = mails[name];
You could also combine those, if you have to determine which algorithm you need to use:
var map = [{
algorithm: function(name) { return name+"#something"; },
names: ["Steve", "Bob", ...]
},{
algorithm: function(name) { return "info#"+name+".org"; },
names: ["Mark", ...]
}];
for (var i=0; i<map.length; i++)
if (map[i].names.indexOf(name) > -1) {
var email = map[i].algorithm(name);
break;
}
or when it is a bit simpler:
var domains = {
"gmail.com": ["Steve", "Bob", ...],
"free.xxx": ["Mark", ...],
...
};
for (var domain in domains)
if (domains[domain].indexOf(name) > -1)
var email = name.toLowerCase()+"#"+domain;
break;
}
Just try to reduce the amount of data to deliver to the client as much as you can.
You can store all the email address in an associative array like
pseudo code
var emailsList = ["steve" => "steve#gmail.com", "bob" => "bob#gmail.com"];
then email = emailsList[name]; will solve your problem
You could create an object in advance:
var name_email_map = {
"Steve": "steve#gmail.com",
"Bob": "bob#gmail.com",
"John": "j7hogli123123#telus.net"
}
This would be easy to output from some server side language with a JSON library for whatever language you're using. There is a list of JSON libraries at the bottom of this page: http://www.json.org/
If you're using PHP on the server side you can just json_encode an associative array, which you may have selected from a database.
var name = 'Bob'; //x.innerHTML;
var email = name_email_map[name];
alert(email); // Alerts bob#gmail.com
alert(name_email_map['John']); // Alerts j7hogli123123#telus.net
I'm building a search suggestion text box control in JavaScript and am trying to find a way to compare the string the user typed against a JSON Object that represents the user's contact list.
The JSON Object looks like this:
var contacts = {
'gmail' : [
{ name : 'Joe Smith', email : 'joe.smith#gmail.com' },
{ name : 'James Simpson', email : 'jim.simpson#gmail.com' }
]
}
Using JSONPath, I've been able to successfully compare the string the user typed against a single field in the contact object (ie. I can test the name, or the email) using the following:
var input = "james";
var search_path = '$.*[?( /' + input + '/i.test(#.name))]';
var results = jsonPath(contacts ,search_path, {resultType:"VALUE"});
Which returns the {James Simpson} contact object, but if I had typed Jim instead of James it would return nothing unless I did two separate JSONPath queries - one against the name and the other against the email.
What I'm looking is an elegant way to do an OR operator with JSONPath so I can test a single string against multiple JSON property values.
Here's the psuedo-code (non-working) that describes what I'm looking for:
var search_path = '$.*[?( /' + input + '/i.test([ #.name, #.email ]))]';
Does anyone know of a way to do this?
I would create a simpler data structure that maps search terms to a contact name. Once you have a contact name, look up the entire record using jsonPath
A better way is to use DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which you can query JSON structure with XPath expressions. This method returns the matches in an array (empty if no matches were found).
Here is a working JSfiddle of the code below;
http://jsfiddle.net/hbi99/z2Erf/
var data = {
"gmail": [
{
"name": "Joe Smith",
"email": "joe.smith#gmail.com"
},
{
"name": "James Simpson",
"email": "jim.simpson#gmail.com"
}
]
},
res = JSON.search( data, '//gmail[contains(., "jim")]' );
console.log( res[0].name );
// James Simpson
The expression '//gmail[contains(., "jim")]' will find all fields under GMAIL regardless of field name. To explicitly constrict the search to the fields "name" and "email", then the query should look like this:
'//gmail[contains(name, "jim") or contains(email, "jim")]'
To get an idea of how powerful XPath is, check out this XPath Evaluator tool;
http://www.defiantjs.com/#xpath_evaluator
If you are using Goessner's parser, you can use the || operator in your expression as follows:
var search_path = '$.*[?(/jim/i.test(#.name) || /jim/i.test(#.email))]';