Pass object to javascript function - function

I have recently been messing around with jQuery on my website, and I have a fairly limited knowledge of Javascript. I am beginning to like the jQuery ability to pass variables to a jQuery function inside the curly braces, like so:
$(somediv).animate({thisisone: 1, thisistwo: 2}, thisisavar);
What I was wondering is how I can write a Javascript function that I can pass items to inside the curly braces? I know you can write functions like this:
function someName(var1, var2, var3...) {
}
but that doesn't support the braces? I also know that you can add no arguments and do this:
function accident() {
for( var i = 0; i < arguments.length; i++ ) {
alert("This accident was caused by " + arguments[i]);
}
}
accident("me","a car","alcohol","a tree that had no right to be in the path of my driving");
but I also want to pass outside variables instead of just a whole line of strings, if that makes sense?
Basically, I want a function that I can pass variables to, like so:
function myFunction(neededcodehere){
//Some code here...
}
myFunction (var1, {"Option 1", "Option 2", "Option 3"}, anothervar);

The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.

function myFunction(arg) {
alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}
myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

Answering normajeans' question about setting default value.
Create a defaults object with same properties and merge with the arguments object
If using ES6:
function yourFunction(args){
let defaults = {opt1: true, opt2: 'something'};
let params = {...defaults, ...args}; // right-most object overwrites
console.log(params.opt1);
}
Older Browsers using Object.assign(target, source):
function yourFunction(args){
var defaults = {opt1: true, opt2: 'something'};
var params = Object.assign(defaults, args) // args overwrites as it is source
console.log(params.opt1);
}

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

My cents.
function readable(args) {
const {opt1, opt2, opt3} = args
console.log(opt1 + opt2 + opt3)
// => "My favorite things"
}
readable({
opt1: "My f"
, opt2: "avori"
, opt3: "te things"
})

Related

Add a block of code with terraform in JSON file

I need to add a conditional when the variable is true, add a block of code in my JSON file but if this variable is false, I need it to do nothing
This is my main.tf
resource "grafana_dashboard" "dashboard_test" {
conficonfig_json = template_file("dashboard.json")
data_source = var.data_source
}
I need add this a block of code in my file JSON
{
"datasource": {
"type": "CloudWatch",
"uid": "${mystring}"
}
}
You should probably switch to using templatefile function [1]. In your example, you would then have:
resource "grafana_dashboard" "dashboard_test" {
config_json = templatefile("dashboard.json", {
mystring = "somevalue"
})
data_source = var.data_source
}
If you do not want to hardcode the value for the mystring variable, you could alternatively use a Terraform variable e.g., mystring = var.mystring. I would also avoid giving just the filename and change the block of code to look like this:
resource "grafana_dashboard" "dashboard_test" {
config_json = templatefile("${path.root}/dashboard.json", {
mystring = var.mystring
})
data_source = var.data_source
}
variable "mystring" {}
More information about using path-based variables is in [2].
[1] https://www.terraform.io/language/functions/templatefile
[2] https://www.terraform.io/language/expressions/references#filesystem-and-workspace-info

How to pass argument values to parameters inside of a objects method as a function

Lets say I have a a object and inside that object I have a function as a property in other words a method, proper JavaScript terminology and with that function I have parameters. How could I pass argument values to that functions parameters would I invoke the argument inside the object or outside the object. Help.
var learningDaily = {
good: true,
smarterDaily: true,
makingMoney: false,
needHelp: true
question: function (question, please) {
if (question typeOf === Number) {
alert("JUST TELL ME HOW TO PASS ARGUMENTS TO PARAMS IN OBJ");
} else if (please === "thank you") {
alert ("thanks")
} else {
alert("thank again");
}
},
getSmarterAfterThis: true
}
Sorry I may have been missing some closing tags bu, pretty much the question is straight forward. Would I invoke the arguments inside the object or outside the object.
help(23, "thank you");
There are several syntax errors in your javascript. It's not clear what the method is trying to accomplish. I gather English is not your first language. I'm afraid the question as-written isn't very clear. That's probably why you're having some trouble getting an answer.
Here's an example that ought to get you going in the right direction:
obj = {
value_label: 'The value of x is: ',
type_label: '. Its type is ',
fun: function(x) {
// Show the value of x with it's type and some label text.
alert(this.value_label + x + this.type_label + typeof(x) + '.')
}
};
// Call the method member fun in obj
obj.fun(42)
You can paste this into https://jsfiddle.net and run it.

How do I loop through a single JSON file for each object to appear on Ionic tinder cards?

So I'm following this tutorial on how to build tinder cards for Ionic 2. The tutorial makes use of randomuser.me's API, but I'd like to use my own JSON file.
Below is my typescript file (though I have omitted some snippets of code that are irrelevant), and the bottom-most function is what I have changed to try retrieving my own JSON data, but it is not working properly :( I think there is something wrong with how I'm trying to loop through the array in my JSON file?
export class HomePage {
#ViewChild('myswing1') swingStack: SwingStackComponent;
#ViewChildren('mycards1') swingCards: QueryList<SwingCardComponent>;
cards: Array<any>;
stackConfig: StackConfig;
recentCard: string = '';
constructor(public http: Http) {
this.stackConfig = {
throwOutConfidence: (offsetX, offsetY, element) => {
return Math.min(Math.abs(offsetX)/(element.offsetWidth/2),1);
},
transform: (element, x, y, r) => {
this.onItemMove(element, x, y, r);
},
throwOutDistance: (d) => {
return 800;
}
};
}
ngAfterViewInit(){
this.swingStack.throwin.subscribe((event: DragEvent) => {
event.target.style.background = '#ffffff';
});
this.cards = [{email: ''}];
this.addNewCards(1);
}
voteUp(like: boolean) {
let removedCard = this.cards.pop();
this.addNewCards(1);
if (like){
this.recentCard = 'You liked: ' + removedCard.email;
} else{
this.recentCard = 'You disliked: ' + removedCard.email;
}
}
addNewCards(count: number){
this.http.get('../../assets/data/pics.json').map(data => data.json().results).subscribe(result => {
for (let val of result){
for (var count = count; count<pic.length; count++){
this.cards.push(val);
}
}
})
}
I have also tried making individual JSON files for the objects and retrieve it this way, but have also failed. I tried console logging the JSON data to see what it retrieves, but is always only the second object. No card appears in the stack after that.
The output for both methods I did were just a single card and an "undefined" string appearing below the card after swiping it.
I'm new to using Ionic and Typescript, by the way (and I'm sort of rushing), so any help or suggestions would be appreciated!
(also here is what my JSON file looks like, if it helps:)
{
"pics": [
{
"name": "balls",
"pic": "assets/img/pics/01.jpg"
},
{
"name": "snowy field",
"pic": "assets/img/pics/02.jpg"
},
{
"name": "hotel bedroom",
"pic": "assets/img/pics/03.png"
},
{
"name": "apartments",
"pic": "assets/img/pics/04.jpg"
}
]
}
You should make sure to understand what a piece of code is actually doing, before you make the required changes to it.
Here is the code you are using to add new cards:
addNewCards(count: number){
this.http.get('https://randomuser.me/api/?results=' + count).map(data => data.json().results).subscribe(result => {
for (let val of result){
for (var count = count; count<pic.length; count++){
this.cards.push(val);
}
}
})
}
Looking at this code, there are a few things that stand out, which we'll break down into steps:
If you want to read your own JSON file, why are you making the request to the randomuser.me API (this.http.get('https://randomuser.me/api/?results' + count)? Here you should enter the path to your own JSON file (this.http.get('../../assets/data/pics.json').
Next, look at what the code does with the results (.map(data => data.json().results)). If we take a look at the JSON that is returned from the API (https://randomuser.me/api/?results=1) we see that the actual results are in the "results" section of the response, so .map(data => data.json().results) is actually saying: take what was returned, convert it to JSON, and give me the results. Since your JSON file does not have such a "results" section, it doesn't make sense to ask for that part of the file. You could change it to .map(data => data.json().pics) to get a list of all the pics.
Now I'm assuming you want to add "count" new cards, so if count is 3 you want to add 3 new cards. First note that this works for the API, because it can create infinite results, but if you want to add 10 cards from your own JSON, you will have to make sure that there actually are at least 10 entries in your JSON.
Let's look at the actual body of the function, step by step: for (let val of result){ loops through every entry returned by the request, so for you, it would loop through all pics. Inside this loop, you are then creating a new loop, which has a few different issues on its own (var "count" has the same name as parameter "count", "pic" is not defined anywhere), but even if the loop was correct, you still loop through all results, so you're not filtering out an amount of results. If you make sure that the length of your list of pics is at least the same amount as count, you could do something more like this:
for (let i = 0; i < count; i++) {
this.cards.push(result[i[);
}
So in the end that would leave us with:
addNewCards(count: number) {
this.http.get('../../assets/data/pics.json')
.map(data => data.json().pics)
.subscribe(result => {
for (let i = 0; i < count; i++) {
this.cards.push(result[i]);
}
})
}
Good luck, and the main lesson here is: understand the code you're using before trying to change it.
Take a look at my ionic-soundboard project as well to see how I use my own JSON files to populate a list of entries.
In addition to Rosco's answer above that fixes my loop, Disqus user JB has provided a good solution to making each object from the JSON file appear on each card.
The card-stack div and ion-card in the HTML file should be appended like so (the zIndex and marginTop properties were modified at the end):
<div swing-stack #myswing1 [stackConfig]="stackConfig" (throwoutleft)="voteUp(true)" (throwoutright)="voteUp(false)" id="card-stack" [style.zIndex]="-1000">
<ion-card #mycards1 swing-card *ngFor="let c of cards; trackBy:trackByCards; let i=index;" [style.zIndex]="-1 * i" [style.marginTop]="i === 0 ? '0px' : '12px'">
And this for the Typescript file, in the voteUp() function:
let removedCard = this.cards.shift();
The difference is the use of shift() (instead of pop()) as this removes the first element from the array in the JSON file. And that's it. Thank you Rosco and JB!!
Note: once you've gone through all the elements in your array it returns to the first element again; it's a endless loop of cards

cscript jscript JSON

This is a very very (very!!!) strange problem.
I have this JSCRIPT that runs on windows XP and 7 using dos CSCRIPT in a file called testJSON.js.
if ( ! this.JSON ) WScript.Echo("JSON DOESN'T EXISTS");
And, well, the message appear, but is an unexpected behavior of JSCRIPT because JSON (as the MSDN documentation says) is one of the default object in the JSCRIPT 5.8 and my system on Windows 7 runs exactly JSCRIPT 5.8.
Now, I have temporary solved this problem (in a little complex script) by creating a new text file and MANUALLY composing a valid JSON string (and, obviously this makes everything works fine even if the system doesn't have the JSCRIPT 5.8 as requested for JSON) but I like to know two things mainly:
1st Why I can't use the JSON object even if my JSCRIPT version is the one that supports that object?
2nd I have read something about the "enabling" of the JSON (and other) unavailable object in my JSCRIPT environment, but all examples is for C# and I like to know if some equivalent code for JSCRIPT exists or not.
You can use eval() to achieve an effect similar to JSON.parse().
eval('obj = {' + JSONstring + '}');
And afterwards, obj.toString() will let you retrieve the data similar to JSON.stringify() (just without the beautify options). See this answer for an example in the wild. The point is, you can create an object from JSON text without having to load any external libraries or switch the interpreter engine.
BIG FAT WARNING!!!
This introduces a vulnerability into the workstation running your code. If you do not control the generation of the JSON you wish to parse, or if it is possible that a 3rd party might modify the JSON between its generation and its interpretation, then consider following Helen's advice. If bad things are in the JSON, it can cause your WScript to do bad things. For example, if your JSON string or file contains the following:
};
var oSH = WSH.CreateObject("wscript.shell"),
cmd = oSH.Exec("%comspec%");
WSH.Sleep(250);
cmd.StdIn.WriteLine("net user pwnd password /add");
WSH.Sleep(250);
cmd.StdIn.WriteLine("net group Administrators pwnd /add");
WSH.Sleep(250);
cmd.Terminate();
var obj = {
"objName": {
"item1": "value 1",
"item2": "value 2"
}
... then parsing it with eval will have just added a new administrator to your computer without any visual indication that it happened.
My advice is to feel free to employ eval for private or casual use; but for widespread deployment, consider including json2.js as Helen suggests. Edit: Or...
htmlfile COM object
You can import the JSON methods by invoking the htmlfile COM object and forcing it into IE9 (or higher) compatibility mode by means of a <META> tag like this:
var htmlfile = WSH.CreateObject('htmlfile'), JSON;
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
With those three lines, the JSON object and methods are copied into the JScript runtime, letting you parse JSON without using eval() or downloading json2.js. You can now do stuff like this:
var pretty = JSON.stringify(JSON.parse(json), null, '\t');
WSH.Echo(pretty);
Here's a breakdown:
// load htmlfile COM object and declare empty JSON object
var htmlfile = WSH.CreateObject('htmlfile'), JSON;
// force htmlfile to load Chakra engine
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
// The following statement is an overloaded compound statement, a code golfing trick.
// The "JSON = htmlfile.parentWindow.JSON" statement is executed first, copying the
// htmlfile COM object's JSON object and methods into "JSON" declared above; then
// "htmlfile.close()" ignores its argument and unloads the now unneeded COM object.
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
See this answer for other methods (json2.js download via XHR, InternetExplorer.Application COM object, an HTA hybrid method, and another example of htmlfile).
Why I can't use the JSON object even if my JSCRIPT version is the one that supports that object?
According to MSDN, Windows Script Host uses the JScript 5.7 feature set by default for backward compatibility. The JScript 5.8 feature set is only used in Internet Explorer in the IE8+ Standards document modes.
You have the following options:
Include json2.js in your script. See this question for options for including external scripts in JScript scripts.
Modify the registry to expose IE9's JScript engine to Windows Script Host. UPD: This solution uses IE's JScript DLLs, but doesn't activate the 5.8 feature set.
Create a JScript execution host programmatically using the Active Script interfaces and use IActiveScriptProperty::SetProperty to force the JScript 5.8 feature set (SCRIPTLANGUAGEVERSION_5_8). Here's a C++ example.
I have read something about the "enabling" of the JSON (and other) unavailable object in my JSCRIPT environment, but all examples is for C# and I like to know if some equivalent code for JSCRIPT exists or not.
Custom script execution hosts can be created only using languages with proper COM support, such as C++, C# etc. JScript can't be used for that, because, for example, it doesn't support out parameters.
JSON encode, decode without default parser: https://gist.github.com/gnh1201/e372f5de2e076dbee205a07eb4064d8d
var $ = {};
/**
* Decode JSON
*
* #param string jsonString - JSON text
*
* #return object
*/
$.json.decode = function(jsonString) {
return (new Function("return " + jsonString)());
};
/**
* Encode JSON
*
* #param object obj - Key/Value object
*
* #return string
*/
$.json.encode = function(obj) {
var items = [];
var isArray = (function(_obj) {
try {
return (_obj instanceof Array);
} catch (e) {
return false;
}
})(obj);
var _toString = function(_obj) {
try {
if(typeof(_obj) == "object") {
return $.json.encode(_obj);
} else {
var s = String(_obj).replace(/"/g, '\\"');
if(typeof(_obj) == "number" || typeof(_obj) == "boolean") {
return s;
} else {
return '"' + s + '"';
}
}
} catch (e) {
return "null";
}
};
for(var k in obj) {
var v = obj[k];
if(!isArray) {
items.push('"' + k + '":' + _toString(v));
} else {
items.push(_toString(v));
}
}
if(!isArray) {
return "{" + items.join(",") + "}";
} else {
return "[" + items.join(",") + "]";
}
};
/**
* Test JSON
*
* #param object obj - Key/Value object
*
* #return boolean
*/
$.json.test = function(obj) {
var t1 = obj;
var t2 = $.json.encode(obj);
$.echo($.json.encode(t1));
var t3 = $.json.decode(t2);
var t4 = $.json.encode(t3);
$.echo(t4);
if(t2 == t4) {
$.echo("success");
return true;
} else {
$.echo("failed");
return false;
}
};
/**
* Echo
*
* #param string txt
*
* #return void
*/
$.echo = function(txt) {
if($.isWScript()) {
WScript.Echo(txt);
} else {
try {
window.alert(txt);
} catch (e) {
console.log(txt);
}
}
};
/**
* Check if WScript
*
* #return bool
*/
$.isWScript = function() {
return typeof(WScript) !== "undefined";
}
// test your data
var t1 = {"a": 1, "b": "banana", "c": {"d": 2, "e": 3}, "f": [100, 200, "3 hundreds", {"g": 4}]};
$.json.test(t1);

Defining recrussive JSON Object notation

Whats wrong in below JSON Object definition
I am trying to create a new JSON Object like below.
So that my idea is to access COMPANYSETUP.HourSetup.initiate();
Not sure the error ?
COMPANYSETUP = {
initiated : false,
companyId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
} },
HourSetup = {
initiated : false,
hourId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
}
}
}
};
Assuming you want a javascript object and not JSON, which disallows functions,
HourSetup =
Should be changed to:
HourSetup :
Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post.
There's a "=" that shouldn't be there. Change it to ":"
JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions.
It should work OK in plain eval()ed JavaScript, but it's not JSON.