Correctly call a JSON function [duplicate] - javascript

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 8 years ago.
How can I call the loadlist function correctly when I have this JSON data?
I am calling like this but it’s not working:
loadlist($('select#selName').get(0), 'pull.php','data.name')
Here is my JSON data:
{
data: [
{
id: "e0b0d8sc5ffd82e",
name: "John",
}
]
}
the function
function loadlist(selobj,url,nameattr) {
$(selobj).empty();
$.getJSON(url,{},function(data)
{
$(selobj).append(
$('<option>Select</option>')
.val('null')
);
$.each(data, function(i,obj)
{
$(selobj).append(
$('<option></option>')
.val(obj[nameattr])
.html(obj[nameattr]));
});
});
}

Your assumption that obj["data.name"] is equal to obj.data.name is wrong. (The equivalent requires two property accesses: obj["data"]["name"])
If you think you might need to do nested property retrievals, you might have better luck passing in a function for retrieving the property. (This also will work if you need to use a dynamically computed value.)
function loadlist(selobj,url,getter) {
$(selobj).empty();
$.getJSON(url,{},function(data)
{
$(selobj).append(
$('<option>Select</option>')
.val('null')
);
$.each(data, function(i,obj)
{
var value = getter(obj);
$(selobj).append(
$('<option></option>')
.val(value)
.html(value));
});
});
}
// Call as follows:
loadlist($('select#selName').get(0), 'pull.php', function (obj) {
return obj.data.name;
});

Related

Pass a parameter in a return array [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 3 years ago.
i need to return this.
GetBooking = function (parameter) {
return Booking.Title[0].parameter;
}
GetPages = function () {
return GetBooking(pages)
}
GetNumber = function () {
return GetBooking(number)
}
booking is a object of arrays, is possible?
If I understand correctly, when doing GetBooking(pages) you expect to get in return Booking.Title[0].pages, meaning GetBooking() function is supposed to be like a middleman to decide which property you want to get from Booking.Title[0].
If I'm correct, then you almost had it right. What will happen in your code is, for example if number was 7, it would look for a property named 7 inside Booking.Title[0].
What you really want to do is this: return Booking.Title[0][parameter], and parameter has to be a string value representing the property you're looking for, meaning you also need to change the rest of the code which would ultimately look like this:
GetBooking = function (parameter) {
return Booking.Title[0][parameter];
}
GetPages = function () {
return GetBooking("pages") ;
}
GetNumber = function () {
return GetBooking("number") ;
}
This will take the string in parameter and look for a property that matches that string inside Booking.Title[0], and return its value.

Javascript ES6: How to expose variables to one function [duplicate]

This question already has answers here:
Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?
(7 answers)
Closed 5 years ago.
For example. I have this code:
export const mergeWrapper = function(aFunction, meta) {
return aFunction;
};
function exampleFunction(temp) {
console.log(temp);
// can print here. without changing exampleFunction method signature.
// in this case should be 'stackoverflow'
console.log(meta);
}
mergeWrapper(exampleFunction, 'stackoverflow')('hello');
I want to do "something" in mergeWrapper. so that, inside aFunction, I can call meta. I have tried something such as:
export const mergeWrapper = function(aFunction, meta) {
aFunction.bind(this);
return aFunction;
};
But it doesn't work. How can I do this.
My idea because I can write some sort of this function using currying. for example:
export const wrapperFunction = function(meta) {
return function(temp) {
console.log(temp);
console.log(meta);
}
}
wrapperFunction('StackOverFlow')('hello');
But written like this will make me write wrapper for all functions. So I want to write a helper.
Thanks
You can do
const mergeWrapper = function(aFunction, meta) {
return aFunction.bind(null, meta);
};
function exampleFunction(meta, temp) {
console.log(temp);
// can print here. without changing exampleFunction method signature.
// in this case should be 'stackoverflow'
console.log(meta);
}
let func = mergeWrapper(exampleFunction, 'stackoverflow');
func('temp');
func('temp2');
Where you have binded meta as the first argument, and all calls would get that value of meta

How to pass array through jquery get function? [duplicate]

This question already has answers here:
Pass array to mvc Action via AJAX
(12 answers)
Closed 6 years ago.
let's assume I have controller method like this
public ActionResult GetSelected(int[] ids)
{
//do something
return Json (ids, JsonRequestBehavior.AllowGet)
}
and in view file I have function which creates array named list.
How can I pass my array to controller using $.get function?
I would do this :
var data = { 1, 2 };
$.ajax({
url: '#Url.Action('GetSelected','ControllerName')',
data: {
getSelected : data
},
success:function(data){
//Do Something With the return data or HttpStatusCode
}
});

Access propertyname while looping through an object [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
As you can see in the code I provided in this question, I try to loop over the properties of an object. All properties are empty objects! I also have another object where I stored a couple of rest-calls (ngResource Stuff which is not important for this question).
Here you can see the "Rest-Calls" stored in $scope.restCalls.
$scope.restCalls = [
{
resource1: RestService.call1,
resource2: RestService.call2,
resource3: RestService.call3
},
{
resource4: RestService.call4,
resource5: RestService.call5,
resource6: RestService.call6
},
{
resource7: RestService.call7,
resource8: RestService.call8,
resource9: RestService.call9
}
];
$scope.data symbolizes the data for each tab. Every object in this array holds the data for the tab. All resources are initilized empty and if the user changes to a page the resources will get stored here.
$scope.data = [
{
resource1: {},
resource2: {},
resource3: {}
},
{
resource4: {},
resource5: {},
resource6: {}
},
{
resource4: {},
resource5: {},
resource6: {}
}
];
So far so good. I gurantee that the calls are working fine. In my application there are multiple tabs and so I want to try to implement some lazy loading :D
Therefore I implemented a function:(the index is defined in the html and is only the a number between 0 and 2)
<uib-tab heading="Tab1" select="tabChange(0)">
... HERE I have some tables which access the $scope.data[0] data
</uib-tab>
<uib-tab heading="Tab2" select="tabChange(1)">
... HERE I have some tables which access the $scope.data[1] data
</uib-tab>
<uib-tab heading="Tab3" select="tabChange(2)">
... HERE I have some tables which access the $scope.data[2] data
</uib-tab>
Here you can see the function:
$scope.tabChange = function (index) {
for (var propertyName in $scope.data[index]) {
$scope.restCalls[index][propertyName]().$promise.then(function (data) {
$scope.data[index][propertyName] = data;
});
}
};
Now lets come to the problem description:
When I change the tab the function tabChange gets fired.
Every Restcall gets fired correctly
The results only get stored into the wrong property of $scope.data[index]. Its always the last propertyname. So for example I change to tab2(index 1).
$scope.data will end up like this:
$scope.data = [
{
resource1: {},
resource2: {},
resource3: {}
},
{
resource4: {},
resource5: {},
resource6: RESULT OBJECT OF THE LAST REST CALL!
},
{
resource7: {},
resource8: {},
resource9: {}
}
];
I think that propertyname is not available in the then function. But I have no clue how to get the name into this function.
The problem arises because the propertyName is in the upper scope of the function and its value is changed before the function is called. You can bind your variable to function scope like below.
$scope.tabChange = function (index) {
for (var propertyName in $scope.data[index]) {
$scope.restCalls[index][propertyName]().$promise.then(function (propertyName,data) {
$scope.data[index][propertyName] = data;
}.bind(null,propertyName));
}
};
You can learn more about javascript closures here and in other sources you can find from Google.

Javascript pass object to function issue

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...
}

Categories

Resources