How to select a variable by a substring with JavaScript - javascript

I have more than 10 javascript variables which change every time the page is refreshed.
I would like to select this variable:
var layer_control_e69649c5e9f941908fcc3173d4dee734 = {
base_layers: {},
overlays: {
"Roads": geo_json_e8253853662b46f985f09f9f27be4df9,
"Intersections": feature_group_d2005a626dee4cb6ac241e03e5110145,
},
};
Only layer_control doesnt not change. The string e69649c5e9f941908fcc3173d4dee734 changes every time the page is refreshed. I would like select this variable using the constant string layer_control.
How can I achieve that?

Can you tell more about how this variable is created and how you are planing to use it? Without further information's I would just suggest to push the variables directly from the input stream into an array. Then you can just point on the position of the variable instead of knowing the name.

One method is to use a regex pattern to test() for the variable name in the appropriate scope. Below, I'm filtering the global object (this) for a key that starts with "layout_control_".
var layer_control_e69649c5e9f941908fcc3173d4dee734 = {
base_layers: {},
overlays: {
"Roads": "test",
"Intersections": "test",
},
};
var varname = Object.keys(this).filter(
key => /^layer_control_/.test(key)
)[0];
console.log(varname);
console.log(this[varname] ?? 'n/a');
For reference, see:
Get all Javascript Variables?

Related

Convert var to const javascript

Is it possible to convert a var to a const?
Say in a scenario like this:
var appname = ''
function setAppName(name) {
appname = name // can I convert this to const now?
}
Basically, this is for a parameter level. Parameter needs to be accessible throughout the file and I want to make it const after first assignment. Is this possible?
To add: If there is any other way besides creating an object with to contain this parameter, it would be better (for a more straightforward solution). I will be working on multiple parameters like this and freezing an object will cause the entire object to freeze. I am hoping to do this on the parameter level.
So either change the parameter to become const. OR (this one I dont think is possible) change the scope of the paramter to global:
function setAppName(name) {
const appname = name // can I change the scope and make this global?
}
Thanks.
Put your app name in an object and freeze it.
let appSettings = { name: "" };
function setAppName(name) {
appSettings.name = name;
Object.freeze(appSettings);
}
Freezing prevents adding, removing and modifying the values of the properties in your object so you should call Object.freeze only once after all other settings (if there are more variables you want to make constant) have been set.
You can do this using a object.
const globals = {
appname: ''
}
function setAppName(name) {
globals.appname = name;
Object.freeze(globals)
// After this point, value of appname cannot be modified
}
Thank you for all your inputs.
I was able to find a workaround for what I was trying to achieve.
var appname = ''
function setAppName(name) {
if (appname === '') {
appname = name // can I convert this to const now?
}
}
Although this doesnt convert it to const, I just added a guard on the setter and it will not be able to overwrite the value now (unless otherwise I am going to initialize again to an empty string).
It is not fool-proof, but this will address my need.
Thanks all!

How to use a jQuery variable that was just made inside a namespace?

I created a namespace to hold variables so that 2 different functions could use them. My first variable uses jQuery and works fine. The second tries to use the variable established in the previous line and fails. It's undefined.
example:
varHolder = {
buildStep4: $('#buildStep4'),
jetSpan: buildStep4.find('#jetSpan')
};
Is there a way to do this properly?
You can capture the value, but use a function to keep it scoped so it doesn't exist after you've created your object.
varHolder = (function() {
var buildStep4 = $('#buildStep4');
return {
buildStep4: buildStep4,
jetSpan: buildStep4.find('#jetSpan')
}
})();
You could also build your object piecemeal:
varHolder = {};
varHolder.buildStep4 = $('#buildStep4');
varHolder.jetSpan = varHolder.buildStep4.find('#jetSpan');
Ids can't be duplicated inside a valid HTML document so it make no sense to provide context to an id selector, you can simply do
jetSpan: $('#jetSpan')

How to push one Javascript object into another Javascript object?

I have one function in which I am iterating across data object which I have fetched from database. In the foreach loop I am trying to create one object(trigger) and pushing it to another variable(Geo) which I will use to put in another variable(triggers). Below is the code-
var Geo={};
array.forEach(this.cityData,lang.hitch(this, function(data,i){
var trigger = {
type: "Inside",
event: {
name: data.Name,
address:data.Address
}
};
var Location= "Location_"+i;
Geo.Location=trigger; // pushing trigger in Geo variable
}));
var triggers = {
Geo //using Geo in trigger
};
is var triggers={Geo}; equivalent to this below code ?
And is my pushing code Geo.Location=trigger; correct ?
var triggers = {
Geo: {
Location_1: trigger1,
Location_2: trigger2 ...... and so on...
}
};
I didn't tested it but it looks like it does almost the same.
Just one thing:
This should give you an exception:
var triggers = {
Geo //using Geo in trigger
};
The statement should be
var triggers = {
'Geo': Geo //using Geo in trigger
};
otherwise triggers will not have a Geo property.
Geo.Location=trigger; is just fine.
A property in an object accessed through dot notation (obj.property) is always considered simply as the propoerty name - i.e. variables are not evaluated. You can have dynamic property names by using the bracket notation: obj[property], which convert "property" to a string (resolving the variable value if necessary) and uses that as the actual property name.
So, try changin:
Geo.Location
to:
Geo[Location]
Edit: I'm not sure what is the expected final result, but if you want to achieve an object as shown in your last code block, the correct syntax should be:
triggers.Geo = Geo;
again, in consideration of the fact that the "Geo" in the dot notation form is simply the string name of the property, and has no relation to the variable of the same name.

Accessing nested objects in javascript

I am trying to run some JavaScript, but it is not working.
I have an object with two properties that are also objects.
var people = {
me: {
name: "Hello"
},
molly: {
name: "Molly"
}
};
And I am trying to make a function that uses a for/in statement and an if statement to list the properties of people.
var search = function (x) {
for (var a in people) {
if (people.a.name === x) {
return people.a;
}
}
};
So the function loops through the properties of people and assigns them to the variable a. Therefore people.a will be equal to a property of people. Then the function returns the property (people.a).
So if I type in me as parameter x, will the function should return the properties for the me object? I put this code in jsLint and jsHint and it passed, but I decided to remove the corrections because they were useless.
I then want to print the object properties in the browser:
var print = search("me");
document.getElementById("p").innerHTML(print);
I have this linked to an html document, with a tag id "p". I have tested javascript in the html document already, so I know that the javascript document is linked properly.
But the code will not work. Does anyone have any suggestions?
I have it working now thanks to the answers. But I thought that it would only print "Hello" to the screen, not { name: "Hello"}.
You need to use people[a], not people.a. The former looks for a property with the name of the value stored in a; the latter looks for a property literally named "a", which of course doesn't exist.
for (var a in people) {
if (people[a].name === x) {
return people[a];
}
}
Fiddle here.
Also, I think you meant search("Hello"), right? If not, then it would just be var search = function(x) { return people[x]; }.
people.a.name
you need to use the bracket operator if you want to access an item by name. Using people.a is literally searching for a member named 'a' instead of a member with the same name as the value of a.
Try:
people[a].name
instead.
4 errors in your code:
replace people.a with people[a]
replace innerHTML() with innerHTML
set HTML like this: document.getElementById("p").innerHTML = print.name;
As in a previous answer, search by name
Code: http://jsfiddle.net/nabil_kadimi/vVSPG/

jQuery data() with multiple parameters?

I want to add data variables to an element before causing a specific behavior, but this may require adding more than one data parameter. How can I accomplish this?
$("#dlg_box").data("r_redirect","index.php").dialog("open");
You can do it like this:
var data = $("#dlg_box").data();
data.r_redirect = "index.php";
data.foo = "bar";
$("#dlg_box").dialog("open");
This was taken from here.
To retrieve your values:
$("#dlg_box").data("r_redirect");
$("#dlg_box").data("foo");
JQuery's data() method also takes an JS Object as a parameter. So you might think of passing {"r_redirect": "index.php", "whatEver": "youWant" ...} etc to pass multiple values match your requirement.
Ultimately, the data() method converts your parameters into an Object. So whether you pass an Object or Key and Value separately should not matter
There are different ways to attach data to a jQuery dialog. If you need to attach multiple Data, I recomend using .data("myData", { /* OBJECT */ }, however you can also use inline string and array data. As far as why yours won't work, with so little code to go on, it could be numerous things. However, I've attached a working example of a Dialog with "params" or data for you to take example from. If you post more of your header code tho, I have a feeling we might find a syntax error or a lack of "doc ready" included. Just some thoughts. Anyway, my example:
jsFiddle
$(function() {
// Set the dialog to not open on load and clear all changes made when closed
$("#dlg").dialog({
autoOpen: false,
modal: true,
close: function(e) {
$(this).children("input").nextAll("p").remove();
}
}) // next i call for my first inner button which will show you how to get "attached" data
.children("#attached").on("click", function(e) {
var dlgData = $("#dlg").data("myData");
$(this).after($("<p />").text(dlgData.data1 + " " + dlgData.data2));
}) // finally, the button that will get the string data that was added in the HTML
.next("#inline").on("click", function(e) {
var dlgData = $("#dlg").data("inline");
$(this).after($("<p />").text(dlgData));
});
// simply open our dialog
$("button").on("click", function(e) {
// HERE data is ATTCHED to our dialog just before opening
$("#dlg").data("myData", { data1: "Hello", data2: "world" }).dialog("open")
});
});
$('#Dialog').data('data1', data1).data('data2', data2).dialog('open');
While Initializing the dialog get the values following:
var data1 = $(this).data('data1');
var data2 = $(this).data('data2');
There are some rules you should be aware of before using this!
ADDING
Adding variables using the object returned from $('.selector').data() works because the data object passes by reference, so anywhere you add a property, it gets added. If you call data() on another element, it gets changed. It is what it is what it is...
Adding an object places a object inside of the data object, as well as "extends the data previously stored with that element." - http://api.jquery.com/data/#entry-longdesc
That means that adding an obj to dataObj becomes
dataObj === { /*previous data*/, obj : { } }
Adding an array does not extend the data previously stored, but doesn't behave the same as a simple value either...
USING
If you have simple values stored, you can place them into variables and do what you want with them without changing the data object.
however
if you are using an object or array to store data on an element, beware!
Just because you store it to a variable does not mean you are not changing data value.
Just because you pass it to a function does not mean you are not changing data values!
It is what it is what it is.. unless it's simple.. then it's just a copy. :p
var data = $("#id").data(); // Get a reference to the data object
data.r_redirect = "index.php"; // Add a string value
data.num = 0; // Add a integer value
data.arr = [0,1,2]; // Add an array
data.obj = { a : "b" }; // Add an object
// but here is where the fun starts!
var r_redirectString = data.r_redirect; // returns "index.php", as expected.. cool
r_redirectString = "changed" // change the value and the compare :
data.r_redirect == r_redirectString // returns false, the values are different
var oArr = data.arr; // Now lets copy this array
oArr.push(3); // and modify it.
data.arr == oArr // should be false? Nope. returns true.
// arrays are passed by reference.
// but..
var oObj = data.obj // what about objects?
oObj["key"] = "value"; // modify the variable and
data.obj["key"] == oObj["key"] // it returns true, too!
So, resources..
What's the best way to store multiple values for jQuery's $.data()?
https://stackoverflow.com/a/5759883/1257652

Categories