Javascript objects matching - javascript

A Javascript object can be used as an associative array.
So my question is how can I automatically set that multiple key's with the same ending match one value?
I'll write an example to be more explicit on what I want.
Something like this:
var handle = {}
handle[*css] = handlers.style;
Every key that ends with "css" should be matched to handlers.style.
Any way to doing this?
PD: Im doing this with server-side javascript with NodeJS

This is possible if you iterate through the object properties and check that the property name matches the desired pattern. Something like:
for (var i in obj) {
if (i.toString().substr(-3) === 'css') {
obj[i] = handlers.style;
}
}

A quick and dirty way:
var handle = {}
name = "article_users_css"
handle[name.substr(name.length-3)] = "something"
or if you can use some symbol to delimit the suffix, you can use this instead:
name.substr(str.lastIndexOf(YOUR_CHAR_OF_CHOICE))

I don't think you can do this. But you can the request pathname before routing the request to your handlers.
See example below:
var path = "mystyle.css"
// var path = "index.html"
// var path = "image.png"
var handle = {};
handle[css] = handlers.style;
handle[html] = handlers.html;
handle[img] = handlers.img;
if (path.match(/.*\.css/)) {
handle[css]();
}
else if (path.match(/.*\.html/)) {
handle[html]();
}
else if ((path.match(/.*\.png/) || path.match(/.*\.jpg/)) {
handle[img]();
}
You can consider using Express that does support routing based on regEx matching

Related

If location.search == '?test=yes' any anything after does something else

I am trying to use the query string in my javascript in my website, is there like a wildcard tag in javascript so it could be like
* = wildcard
var x = location.search;
if (x=='?test=yes') {
window.location.replace('http://google.com')
}
else {
if (x=='?test=yes&*=123') {
window.location.replace('http://youtube.com')
}
}
Would this be possible?
Just use includes:
const x = "https://example.com?test=yes&*=123";
console.log(x.includes("?test=yes"));
You could alternatively use a regular expression:
const x = "https://example.com?test=yes&*=123";
console.log(/]?test=yes/.test(x));
There is a built in class to handle this now.
var params = new URL(location.href).searchParams;
This will return a URLSearchParams object that you can use to check the query string.
if(params.has('test')){
console.log(params.get('test'));
}
One way of achieving this would be with .includes(), wherein you can simply check that x contains the starting string ?test=yes:
const x = '?test=yes&*=123';
if (x.includes('?test=yes')) {
console.log('yes');
}

Adding values to a specific property in an array(?) in javascript

Im wondering how I can add a value to to main in this array.
var herpderp = {
"main": ["stuff", "stuff"]
};
so it would look like:
var herpderp = {
"main": ["stuff1", "stuff2", "stuff3"]
};
Preferably I'd like to create this kind of structure from a couple of strings in a fucntion if that's possible. So says I have this
var strings = {"stuff1","stuff2", "stuff3"}
for (each element of strings) {
what do I do here to get the structure above
}
Alternatively another function to search through an Array of objects on a specifik property. Right now Im trying to use this to filter through the array, maybe there's another way?
var arrays = search;
var result = events.filter(function(item) {
for (var prop in arrays)
if (arrays[prop].indexOf(item[prop]) == -1)
return false;
return true;
});
Thank you kindly for any reply!
herpderp.main is your array, so you can add to the array like so:
herpderp.main.push(value)
If the key for your array was not a valid variable name (it starts with a number, for example), you could use bracket notation instead:
herpderp['123key'].push(value)
Actually, you are changing the previous values beside adding a new element.
var herpderp = {
"main": ["stuff", "stuff"]
};
var strings = ["stuff1","stuff2", "stuff3"];
strings.forEach(function(value,key){
herpderp.main[key] = value;
});
console.log(herpderp);

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Javascript: Removing an object from array by checking it's attribute

I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?
var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);
var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);
In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml
try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories