Currently I have implemented a Javascript Ajax search where if user types a city name I am populating the name in the search result. Problem is there are cities which have alternate names (for example Mumbai has Bombay as alternate name.....Bangalore has Bengaluru as alternate name). I want to map the alternate names of the city to the correct name using javascript. ALSO there might be multiple alternate names for the city not only one. so how can I map alternate cities name to correct one using javascript.
var duplicateNameCities = {
"Bengaluru": "Bangalore",
"Mumbai": "Bombay"
};
// when you're given a string, run it through this map first
city = duplicateNameCities[city] || city;
However, it feels like the server side should handle this
var alternates = {
Bombay : "Mumbai",
Bengaluru : "Bangalore",
}
var userCity = obtainUserInputSomehow()
if (alternates.hasOwnProperty(userCity)) { userCity = alternates[userCity] }
// after this userCity will have "Mumbai" if user entered "Bombay" or "Mumbai".
// add as many aliases as you need.
Related
function favPlayers(arr){
for(i=0;i<arr.length;i++)
{
console.log(arr[i]);
}
console.log() // output I want here is "These are my fav (sport name) players" according to the sports I've given as an input
}
var cricket = ["dhoni", "Virat", "sachin", "ponting", "steyn", "abd"]
var football = ["CR7", "messi", "bale", "mbappe", "haaland", "bruno"]
In this function, I need to print the variabe name of the array alone based on my input.
like if I pass football as a paramtere in second console football must be printed out in the "sport name" area. eg my output should be ("These are my fav football players")
console.log("These are my favourite" + arr + "players");
I tried this but instead it prints all the players name again.
Is there anyway to do this? please let me know.
This is my first stack overflow query and I am learning javascript as a noobie so if my question explanationa and my english is not that good pardon me :)
With a little rearranging, yes, this is possible. Use an Object and the sports names as keys:
function favPlayers(arrName){
for(i=0;i<sports[arrName].length;i++)
{
console.log(sports[arrName][i]);
}
console.log(`These are my fav ${arrName} players`); // output I want here is "These are my fav (sport name) players" according to the sports I've given as an input
}
var sports = {
cricket: ["dhoni", "Virat", "sachin", "ponting", "steyn", "abd"],
football: ["CR7", "messi", "bale", "mbappe", "haaland", "bruno"]
}
favPlayers("football");
What I want to do is change the url.
Replace the Object word with an event parameter called e1.
Replace the word field with the event parameter e2.
I know this code is not working.
But I don't know how to do it.
The following is my code that I just wrote.
function getAllFieldValue(e1,e2) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = 'test123.my.salesforce.com/services/data/v44.0/queryAll?q=SELECT Field FROM Object';
var url = url.replace('Object',e1);
var url = url.replace('Field',e2);
var response = UrlFetchApp.fetch(url,getUrlFetchOptions());
var json = response.getContentText();
var data = JSON.parse(json);
var fieldValues = data.records;
for(var i=0;i<fieldValues.length;i++){
var fieldValue = fieldValues[i].e;
ss.getRange(i+1,1).setValue(fieldValue);
}
}
I want to take the data from another database through this code and put it in the Google spreadsheet.
For e1, it means the object value selected in the dropbox.
For e2, it means the field of the object selected in the drop box.
Is there a way to use two event parameters for one function?
I look forward to hearing from you.
====================
Please understand that I am using a translator because I am not good at English.
Checking fieldValues[i] in Logger.log returns the following values:
[{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03VAAT
},
Name=University of Arizona
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03TAAT
},
Name=United Oil & Gas Corp.
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03ZAAT
},
Name=sForce
}]
The issues I am currently experiencing are as follows.
If I select 'Name' from the drop-down list, ec2 becomes 'Name'.
As far as I'm concerned,
var fieldName = fieldValues[i].e2 is
var fieldName = fieldValues[i].Name
It means that.
I think fieldValues[i].e2 should return the values of University of Arizona, United Oil & Gas Corp, sForce.
But in reality nothing is returned.
var fieldName = fieldValues[i].Name works properly.
I think there is a problem with fieldValues[i].e2
This is the problem I'm currently experiencing.
There was no problem with the parameters e1, e2, which I thought was a problem. The reason why the code did not work is because of the for loop var fieldValue = fieldValues[i].e; Because it didn't work properly.
var fieldName = fieldValues[i].e2
to
var fieldName = fieldValues[i][e2]
After modifying it like this, the code works properly.
I'm working with an NBA API where one of the features is finding players by their last name.
The issue I have; is that multiple players can have the same last name, of course.
An example of the response from the API when sorting with last names:
"players": [
0: {
"firstName":"Anthony"
"lastName":"Davis"
"teamId":"17"
"yearsPro":"9"
"collegeName":"Kentucky"
"country":"USA"
"playerId":"126"
"dateOfBirth":"1993-03-11"
"affiliation":"Kentucky/USA"
"startNba":"2012"
"heightInMeters":"2.08"
"weightInKilograms":"114.8"
1: {
"firstName":"Deyonta"
"lastName":"Davis"
"teamId":"14"
"yearsPro":"3"
"collegeName":"Michigan State"
"country":"USA"
"playerId":"127"
"dateOfBirth":"1996-12-02"
"affiliation":"Michigan State/USA"
"startNba":"2016"
"heightInMeters":"2.11"
"weightInKilograms":"107.5"
}
I limited the results here, but it goes on and on, etc.
So, I am looking to do two things:
First, extract/filter the correct player using their first name and last name.
In said extraction, I still need the complete array information when it is matched.
So essentially, I want 'Deyonta Davis', but when found - I also need the rest of said player's information (years pro, college, country, etc.)
I already have a command set up to retrieve the first result of the nested data in this API via last name - where the command takes the last name you input and sends the first result. The precise problem is that the first result is likely not to be the guy you are looking for.
The goal is to include first & last name to avoid pulling the wrong player.
A snippet of how I currently call the information via last name:
// Calling API
const splitmsg = message.content.split(' ')
var lastnameurl = "https://api-nba-v1.p.rapidapi.com/players/lastName/" + splitmsg[1];
axios.get(lastnameurl, {
headers: {
"x-rapidapi-key": apikey,
"x-rapidapi-host": apihost
}
// Extracting Player Information (first result)
var playerfirstname = response.data.api.players[0].firstName;
var playerlastname = response.data.api.players[0].lastName;
var collegename = response.data.api.players[0].collegeName;
var countryname = response.data.api.players[0].country;
var playerDOB = response.data.api.players[0].dateOfBirth;
var yrspro = response.data.api.players[0].yearsPro;
var startednba = response.data.api.players[0].startNba;
Any help would be appreciated, thank you.
If I understand the question correctly the task is:
Retrieve first matching object from an array where properties firstName and lastName equal to desired values.
To achieve this you could use build in find function.
const player = array.find(el => {
return el.firstName === "Deyonta" && el.lastName === "Davis"
});
Keep in mind if there is no such object in array the player will be undefined.
I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
Hopefully this code explains things better:
// before search
var singleAddress = "Mount Farm";
var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
// this is the record which the search needs to be run against
plot = [{
postcode: "MK1",
area: "Denbigh, Mount Farm",
}, {
postcode: "MK2",
area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
}, {
postcode: "MK3",
area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
}, {
postcode: "MK4",
area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
}, {
postcode: "MK5",
area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
}]
// after search is run then:
// var singleAddress = "Mount Farm, MK1"
// var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
Fiddle here
All right, so you can't easily change the original data format. How big is the actual record and how often does it update? 'cause if it's not huge and doesn't change several times per second and you're going to do many lookups, it would be more efficient to create the mapping I mentionned and then read from it, than to look through the original structure every time. I'm going to assume so in this answer. Hope it helps.
Another assumption in this code: that each area has exactly one postcode.
function convertPlot(plot)
{
var mapping={}
plot.forEach(function (r){
var locations=r.area.split(/,\s*/)
for(var i=0, loc; loc=locations[i]; i++)
mapping[loc]=r.postcode
})
return mapping
}
Simply do this when you get the plot:
mapping=convertPlot(plot)
Then the lookup function becomes trivial:
function lookup(adr)
{
if('string' == typeof adr)
return adr+", "+mapping[adr]
if(('object' == typeof adr) && adr instanceof Array)
return adr.map(lookup)
throw new TypeError("cannot look up something that isn't a string or array or strings")
}
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))]';