How to push one Javascript object into another Javascript object? - javascript

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.

Related

How to select a variable by a substring with 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?

Javascript remove double quotes in from object's value

I'm generating a JavaScript object in a Java class for use in javascript the result looks like this:
var gridDefinition = {"width":"100%",
"height":700,
"sortable":true,
"columns"[{"datafield":"id","datatype":"string","width":300,"hidden":true,"text":"ID"},
{"datafield":"lastname","datatype":"string","cellsrenderer":"renderer_openEntry","width":300,"text":"Nachname"},
{"datafield":"firstname","datatype":"string","width":200,"text":"Vorname"},
{"datafield":"officePhoneNumber","datatype":"string","width":150,"text":"Telefon"},
{"datafield":"companyName","datatype":"string","width":300,"text":"Firma"},
{"datafield":"mailServer","datatype":"string","width":200,"text":"Mail-Server"},
{"datafield":"mailFile","datatype":"string","width":400,"text":"Mail-Datei"}]} ;
cellsrenderer is a callback function name. How can I remove the doublequotes surrounding renderer_link? The result line should look like this:
{"datafield":"lastname","datatype":"string","cellsrenderer":renderer_openEntry,"width":300,"text":"Nachname"},
How to "remove the quotes" is the wrong question to ask. At the moment the code is running, there are no quotes that can be removed.
What you need is a map that maps a name to a variable, e.g.
var myFunctions = {
renderer_openEntry: renderer_openEntry,
// other functions
};
and then process the object to update the values of all cellsrender proeprties to refer to the value from the map instead of the string:
gridDefinition.columns.forEachfunction(column) {
if (column.cellsrenderer) {
column.cellsrenderer = myFunctions[column.cellsrenderer];
}
});

Javascript function not called properly

I am trying to click on the first radio button and it will assign variables distSelected and weapon some values from the object engDistanceObject. I suspect my HTML might not be written correctly... specifically the input tags.
https://jsfiddle.net/Natronox/sbojaxm4/#&togetherjs=zb80KxkQzm
var engDistanceObject = {
short: ["100m-300m","416 Assault Rifle"],
long: ["300m-1000m","M110 DMR"]
};
var distSelected;
var weapon;
function distanceClick(item){
distSelected = engDistanceObject.item[0];
weapon = engDistanceObject.item[1];
console.log(distSelected,weapon);
};
Use your short and long properties instead of item. You don't have an item property name in your object.
.short[0]
.short[1]
To access dynamic properties, you can't use the . syntax. It ignores variables that might have the same name as the property you're trying to access, and instead will try to access the non-existent item property.
Instead, use the bracket syntax [], which allow a string to be used to access dynamic properties. This means that you need to pass a string as a parameter to your function.
Your HTML event handlers will need quotes around the parameters:
onclick="distanceClick('long')"
And then use the bracket syntax in your JS:
function distanceClick(item){
distSelected = engDistanceObject[item][0];
weapon = engDistanceObject[item][1];
console.log(distSelected, weapon);
}

Meteor passing MongoDB selector from parameter

I want to so some query that is as same as LIKE from the good old school rdbms, so I have to use some sort of regex for that.
When I try this, it works fine
Countdowns.find({"name":{ "$regex": /ANW/ }},{ sort: {regDate: -1 }});
the value returns correctly. However when I build the mongoDb selector (the first JSON param for the function) it never works.
var key = Session.get('searchKey');
var field = Session.get('searchField');
var temp = '{"'+ field +'":{ "$regex": /'+key+'/ }}';
var selector = JSON.parse(JSON.stringify(temp));
Countdowns.find(selector,{ sort: {regDate: -1 }});
When i test it out (using try-catch during JSON.parse), the JSON object was built without any error but somehow the function (find()) fails to operate when i pass it as variable.
Is there other way to build the selector?
I have tested on the console and this is what I got.
Try to make it this way
var key = Session.get('key'), field = Session.get('field');
var selector = {};
selector[field] = { $regex : new RegExp(key) };
With this you will get:
And that should be acceptable for minimongo.
Why JSON.parse didn't work? At the point you where passing temp this is what it looked like:
You already had a string before passing it to JSON.stringify. But wait! You would say, if I instead pass it to JSON.parse it will work? Let see:
Nope. The forward slash has to be properly formatted and even then you'll get a string for the $regex, and you want a RegExp object.
So the way one end ups doing this is what I wrote you before. First you define the variable that will hold your selector for the database as an object and with that you construct your selector.

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