This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
Parse query string in JavaScript
http://www.example.org/search?q=example&another=test&again=more
How can I create three sepearate variables in jQuery with the values example, test, and more?
In other words, how can I extract a query from a URL based on its position (first, second, third, etc.) in the URL or based on the &another= part (not sure what it's called) of the query?
I use this method:
var query = window.location.split('?')[1]; // or http://www.example.org/search?q=example&another=test&again=more
var query_obj = unserialize(query);
function unserialize(query) {
var pair, params = {};
query = query.replace(/^\?/, '').split(/&/);
for (pair in query) {
pair = query[pair].split('=');
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return params;
}
So you'll have your variables in the query_obj like this: query_obj.test
I found the function over the internet a while ago so I can't provide a link. Sorry and thanks to whoever published it first.
I use an existing plugin for tasks like these: https://github.com/allmarkedup/jQuery-URL-Parser
Related
This question already has answers here:
How I can use "LIKE" operator on mongoose?
(7 answers)
Closed 1 year ago.
I am making a dictionary web app and now I am trying to make a search engine. I want to partly enter a word and get all of the similar matches. For example, I enter "ava", and get "lava" and "available" back. Mongoose has a method to do that but I need to enclose my query into slashes (like this /query/). I can do that with a string but I don't know how to put a variable in there in order to make a user search.
// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();
Here's my code:
app.post("/search", function(req, res){
let search = req.body.wordSearch;
console.log(req.body.wordSearch);
Dicword.find({word: /search/i}, function(err, searchRes) {
search = searchRes;
res.render("search", {search: search});
} );
})
I use let search to store the query and a result of a search but when I put it in find method with slashes /search/, it gets recognized as a string and not a variable. How can I use a variable there?
Instead of
{ word: /search/i }
Write like this
{ word: `/${search}/i` }
This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}
members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I'm trying to process data from the OpenWeather API for multiple cities. This is what the data looks like:
{
"cnt":20,
"list":[
{
"coord":{"lon":-99.13,"lat":19.43},
"sys":{"country":"MX","timezone":-18000,"sunrise":1591012665,"sunset":1591060290},
"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
"main":{"temp":12.88,"feels_like":11.84,"temp_min":12.78,"temp_max":13,"pressure":1027,"humidity":82},
"visibility":8047,
"wind":{"speed":1.5,"deg":60},
"clouds":{"all":20},
"dt":1591013691,
"id":3530597,
"name":"Mexico City"},
{...next cities...}
]
}
I'm fine with everything, except the weather part(3rd line). I want to assign each value to a separate variable like so:
weatherid = 801
main = "Clouds"
description = "few clouds"
I've tried stuff around the lines of
main = citydata.list[i].weather.main; (doesn't work)
main = citydata.list[i].weather.main(); (doesn't work)
main = Object.values(citydata.list[i].weather);
and quite a few things in between.
(Well, the last one kinda does something but I don't end up with something different, and when I try and get the values it's always "undefined")
So, what's the simplest way of accessing that data and storing each part of it in its own variable.
Or even just converting the contents of "main" into an array (I'm assuming those questions overlap)
Thanks!
try that:
const data = JSON.parse(req.data);
const main = data.list[0].weather.main
This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 5 years ago.
Let's say my url atm is
http://test.com/?city=toronto
I'm able to get the requestURL string that is
/?city=toronto
From here, I was wondering if there is a built in function or a standard procedure of extracting the word "toronto" or any other word that comes after the = from the string.
A standard procedure (as you mentioned) of doing this, you can get all the parameter values including value of city or any other parameter you may add to it.
var values = new URL('http://test.com/?city=toronto').searchParams.values();
for(var value of values){
console.log(value);
}
UPDATE
As #taystack mentioned in the comment, if you only want the value of a specific parameter (city) in this case, you can use:
new URL('http://test.com/?city=toronto').searchParams.get('city');
Use split();
var url = '/?city=toronto'.split('=');
console.log(url[1]);
Node.js has a new module called URL, which encodes the semantics of a url string. You don’t need to do any string manipulation.
const URL = require('url')
let my_url = new URL('http://test.com/?city=toronto')
URL#search returns the string representing the search:
my_url.search // '?city=toronto'
URL#query returns the search string excluding ?:
my_url.query // 'city=toronto'
and URL#searchParams returns an object encoding the search string:
my_url.searchParams // something kind of like {'city':'toronto'}
my_url.searchParams.get('city') // 'toronto'
my_url.searchParams.keys() // ['city'] (all the keys)
my_url.searchParams.values() // ['toronto'] (all the values)
This question already has answers here:
JSON find in JavaScript
(7 answers)
Closed 7 years ago.
I receive data as a JSON object, like this:
[{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}]
I know I can access the data like this:
alert(obj[0].amount);
But I would like to be able to access the data like this:
obj[transid].amount
where transid is a previously declared and assigned variable, like this:
var transid = 1091;
alert(obj[transid].amount); //returns -549
If this is even possible, I assume the JSON object would have to be restructured (I don't have any control over how I receive the JSON object), but I don't really have any idea how to go about this. I've tried Googling and SOing, but I am just not sure what to look for.
Edit: I've looked at the proposed duplicate question as suggested by Travis J, and I do not agree that this is a duplicate. I'm not asking to loop through data. I'm asking for methods to reference by a specific index, given JSON that I don't control how it comes to me. The accepted answer in the proposed duplicate shows how I envision the code to look (in the second code box), but I don't think it really answers my question. Another answer in the proposed duplicate, posted by Hakan Bilgin, suggests using defiantjs, which would probably work. However, there are many other methods, some of which have been provided as answers to this question already.
You can use filter like
obj.filter(function(o){
return o['transid'] === 1091;
})[0].amount // -549
You can add the above function to Array's prototype like
Array.prototype.get = function(id){
return Array.prototype.filter.call(this,function(obj){
return obj['transid'] === id;
})[0].amount
}
And use it like
obj.get(1091); // -549
It is up to you to add proper validation like dealing with not found keys and duplicates.
You can create a new object from that one. Something like this
var transactionArray = [
{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}
];
var transactionsById = {};
transactionArray.forEach(function(element) {
transactionsById[element.transid] = element;
});
var transid = 1091;
alert(transactionsById[transid].amount); //returns -549
Where transactionArray is what you refer to as obj in your question.