Javascript pass object to function issue - javascript

In javascript, I have an object that I am trying to pass but not working:
var inf1= { ID: "34343434" };
What I like to do in javascript is to pass this object to a function .
I am not sure how to do this.
I have the calling function as such
function getinf(inf1)
{
var samp = JSON.parse(inf1);
alert(samp.ID);
}

You use JSON.parse() on a JSON formatted string. You don't use it on a javascript object. JSON is a text format.
Your inf1 variable is already a javascript object so there is no need to parse it.
This should work just fine:
var inf1= { ID: "34343434" };
function getinf(item)
{
alert(item.ID);
}
getinf(inf1);

Careful, a few things:
JSON.parse() is for strings
And to pass the value you could do:
var inf1= { ID: "34343434" };
function getinf(obj)
{
//code using obj...
//you can acess obj.ID if you want
}
getInf(inf1); //or any obj you want
or
var inf1= { ID: "34343434" };
function getinf()
{
//code using inf1...
}

Related

How to return a Javascript function in an API?

I need to return the following in a custom REST API I am building using Jackson.
The following is simply a Javascript function.
Is there a way to return a javascript function as is? Without returning it as string, and then having to parse it on the front end.
{
yFormat: (timestamp) => { return date.getDurationValue(timestamp); }
}
So you create a function and use toString() to get it as string.
Then you add it to you object and create json string from it.
In handler you convert it back to function and use it.
var testFunc = function(e){alert(e);}
var funcAsString = testFunc.toString();
alert(funcAsString);
var json = { "one": 700, "two": funcAsString };
var parameters = JSON.parse( JSON.stringify(json));
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"
Used How do I convert a JSON string to a function in javascript? post to create that solution.

array.filter by object property, argument is not defined

I am trying to write a filter function that takes 2 parameters:
id type and the actual id value. Using these IDs, I want to filter an array of objects.For example, here I am trying to get a new array that only includes the values with the name of 'Mike'.
object:
var sample = [
{ name: 'Mike'},
{ name: 'John'}
];
filter function:
function filterById(obj, parameter, id) {
return obj.parameter == id;
}
this:
console.log(sample.filter(filterById(name, 'Mike')));
returns name is not defined.
Do I need to pass in the actual array as well? Is it possible to pass parameters into filter functions at all?
You would need to pass the "parameter" as a string too, and use the square bracket notation, and for this all to work your filterById function would itself have to return a function which matches the function used by Array.prototype.filter:
var sample = [
{ name: 'Mike'},
{ name: 'John'}
];
function filterById(parameter, id) {
return function(obj){
return obj[parameter] == id;
}
}
console.log(sample.filter(filterById('name', 'Mike')));
You don't have to invoke the function by yourself – it is a high-order function, so you have to provide only function. And here we come to the problem – you want to pass arguments there, but you can't!
So, there are few approaches. The first one is just to return another function, which will keep data in closure:
function filterById(parameter, id) {
return function(item) {
return item[parameter] == id;
}
}
The second option is to create another function via .bind, which is close to the idea of partial application. It will create new function with pre-defined parameters. They are always first, so you have to move actual item definition to the last position:
function filterById(parameter, id, item) {
return item[parameter] === id;
}
// we can create function for the future reference:
const filterByMike = filterById.bind(null, 'name', 'Mike');
sample.filter(filterByMike);
It's hard to say what is better, but I'd personally prefer the second approach.

Passing a viewmodel object to a jquery variable

I need to access the members of viewmodel object in a javascript function and have tried to do this by assigning it to a jscript variable like this:
var teamEdit = (function() {
return {
communityGroups: '#Model.CommunityGroups'
}
});
$(function() {
....
var groups = teamEdit.communityGroups;
Unfortunately the groups variable comes out as undefined even though 'CommunityGroups' is defintely populated. (checked by debugging controller)
#Model.CommunityGroups would simply call ToString() that would emit something like "System.Collections.Generic.List`1[CommunityGroup]".
You need to serialize it to JSON instead:
communityGroups: #Html.Raw(Json.Encode(Model.CommunityGroups))
The issue with your code was you were try to access the function teamEdit with out () change it to teamEdit()
See the below.
var teamEdit = (function() {
return {
communityGroups: '#Model.CommunityGroups'
}
});
$(function() {
....
var groups = teamEdit().communityGroups;

Dynamic javascript function declaration

I'm working on a code where I must pass a different function to some objects.
In this case, I'm trying to pass a different function for the onchange event. So currently what I got is something like this this:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList){
var doFunction = function() {
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}
The problem here I believe is that I'm afraid it will execute the code as it is declared and not with the values of the actual variables.
Is there a way to pass the function with the values as it executes? or will the variables get parsed the way its written?
It's the classic function in a loop problem. You need to understand how closures work.
Read the "Example 3" part of this answer carefully. The whole How do JavaScript closures work? question, too.
Another example that might help understand intuitively:
var key = 5;
var onchange = function () {
console.log(key);
};
onchange(); // 5
key = 10; // the loop reassigns the key on each iteration
onchange(); // 10
This is how it should be done:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList)
{
(function(key)
{
var doFunction = function()
{
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}(key))
}

javaScript jQuery function, how do i pass variables

What is wrong with my code. How do i pass attrfull to the inside. The way i have it done, if i run the function editsubmit($selected, size), $selected is inserted properly but i'm getting attrfull instead of size.
function editsubmit(attr, attrfull) {
if (attr.length) {
attr.val().length ? $selectedinput.attr({
attrfull: attr.val()
}) : $selectedinput.removeAttr(attrfull);
}
}
$selected is a variable and attrfull i a string. Do i need double qoutes around the string when i run the function like editsubmit($selected,'size').
Try
function editsubmit(attr, attrfull) {
if (attr.length) {
attr.val().length ? $selectedinput.attr(attrfull, attr.val()) : $selectedinput.removeAttr(attrfull);
}
}
Yes, you do need it to be a string (in double quotes), or else it will think you're trying to pass a variable reference.
The problem is this:
{attrfull: attr.val()}
I think you want it to be
{size: (whatever attr.val() is)}
So:
function editsubmit(attr, attrfull) {
if (attr.length) {
if (attr.val().length) {
var myObj = {};
myObj[attrfull] = attr.val();
$selectedinput.attr(myObj);
} else {
$selectedinput.removeAttr(attrfull);
}
}
}

Categories

Resources