jQuery: Get first object in array after Ajax call - javascript

I'm trying to get the first object returned by the ajax call before doing the each() loop through it. Here's the code that works for the each:
$.each(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
What I'd like to do is this:
$.each.first(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
But I'm getting this error:
VM1172:38 Uncaught TypeError: $.each.first is not a function
doing a $.get(obj.DATA)..... doesn't work either.

$.each.first(obj.DATA[0], function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});

Related

get specific value from response.data angular js

i want to get specific value from a response, here is my js
$scope.cari = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
$scope.reslogin2 = response.data.lsmenu.idmenu;
console.log($scope.reslogin);
console.log($scope.reslogin2);
});
};
but when i console.log the $scope.reslogin2gives me undefined value. here is my response
[{"userid":"1234",
"username":"ristian",
"posisi":"ITSupport",
"lsmenu":[{"idmenu":"1","parentidmenu":"11","parentnamemenu":"Monitoring","urlmenu":"lalala.html"}]}]
According to what you posted, your response is an array (so is the lsmenu). Therefore you should get the first element of the array and also the first element from the lsmenu.
$scope.cari = function () {
$http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
$scope.reslogin = response.data;
$scope.reslogin2 = response.data[0].lsmenu[0].idmenu;
console.log($scope.reslogin);
console.log($scope.reslogin2);
});
};
It should be, response.data is an array and lsmenu is also an array
$scope.reslogin2 = response.data[0].lsmenu[0].idmenu;

How to extract data from array in javascript

I have an object (array type) ,its console representation looks like following image . please see the image
This array is created by restangulr using following code ,
restangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = { status: response.status };
feedBackFactory.showFeedBack(item);
}
return response.data;
});
How can I read the elements from this array, I want to extract properties like paginginfo ,also object collection
// The EDIT :1 js libraries I used here angularjsu 1.3.4, and restangular 1.4
My app.js : here I configured rest angular provider
restangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
if (operation == "getList") {
var extractedData;
extractedData = data.result;
extractedData.paginginfo = data.paginginfo;
return extractedData;
}
if (operation != "get") {
var item = {
status: response.status
};
feedBackFactory.showFeedBack(item);
}
return response.data;
});
// according to my knowledge this function will intercept every ajax call (api calls) and modify the response , unfortunately I need to apply custom modification because the getlist method must return collection but my api returning object, so according to restangular ,the above code is the possible solution, and here its fine its fetching the data.
userservice.js : this is angular service which using restangular
function(restangular) {
var resourceBase = restangular.all("account");
this.getUsers = function(pagenumber, recordsize) {
var resultArray = resourceBase.getList({
page: pagenumber,
size: recordsize
}).$object;
};
};
according to my knowledge .$object in restangulr resolve the promise and bring back the data, also I am getting the resultArray its looks like in the image in the console, here I can log this array so I think I got all the data from server and filled in this object. I applied some array accessing techniques available jquery and JavaScript like index base accessing , associate accessing but I am getting undefined ie.
resultArray[1] //undifiend;
In angular you can use angular.forEach(items, function(item){ //your code here});
Where items is the array you want to traverse.
If you want to access to one specific position use [], for example var item= items[5].
Then you can do item.property.
UPDATE
Your problem is that you are setting properties in an Array JS Object:
extractedData.paginginfo = data.paginginfo;
You should return the object data like it is and in your controller do something like:
var results= data.result;
var pagInfo= data.paginationInfo;
angular.forEach(results,function(result){});
It looks like the array is numerically indexed (0..1..5); you should be able to simply iterate through it using ForEach (in Angular) or .each (in Jquery).
Something like (JQuery):
$.each(array, function(key, value)
{
// key would be the numerical index; value is the key:value pair of the array index's element.
console.log(value.firstname); // should print the firstname of the first element.
});
First of all, as I said in the comments, you shouldn't be attaching named properties to arrays. Return an object thact contains what you need:
if (operation == "getList") {
return { values: data.result, paging: data.pagingInfo };
}
The getList() method returns a promise, so you need to use that:
this.getUsers = function(pagenumber, recordsize) {
resourceBase.getList({
page: pagenumber,
size: recordsize
}).then(function (data) {
console.log(data.values[0]);
console.log(data.paging.totalRecords);
});
};

Keep getting [object, Object] from array for $.each

I keep getting [object, Object] from array for $.each when i try and alert it.
Below is the code I am using, I have tried several different ways but this seems to be the way that works the best.
Could someone please help me out
var min_chats = [];
$(function () {
$(".append_chat").click(function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
min_chats.push({
"chatid": chatid,
"data": data
});
});
$("#max_close").live("click", function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
$.each(min_chats, function (key, val) {
alert(key + val);
});
});
});
The callback parameters for $.each are index and value, not key and value.
In your case key will contain the index of the array and val will contain your object containing 2 properties: chatid and data.
So your code should look like:
$.each(min_chats, function(index, val) {
alert(val.chatid + val.data);
});
$.each documentation: http://api.jquery.com/jquery.each/

Cannot read property '#<Object>' of undefined getting error?

I have json file . I am trying to get json data from json file .then I need to convert the json (change key and value) key and value because this puglin require in that formate in key and value and https://github.com/nimbly/angular-formly .
But my problem is that istead for getting form from this plugin.
Cannot read property '#<Object>' of undefined
can you please tell where I am wrong ?
Issue reproduce .click on button (get json from a file).then you will see in console that error .I want to show form when I click to button (click to grt json A)
Plunker
http://plnkr.co/edit/bbd6D828TU8TpZYre9D0?p=preview
$scope.getFromAFile= function () {
// body...
var inputs=[];
$http.get('a.json').success (function(data){
var a=changeData(data);
console.log('pp');
console.log(data.studentName);
$scope.formFields.push(a['input']);
}).error(function(err){
alert(err);
});
}
function changeData(data) {
var map = { NUMBER: "number", TEXT: "text", SWITCH: "select" };
// data is an object - use for .. in to enumerate
for (var key in data.input) {
var e = data.input[key]; // alias for efficient structure dereferencing
e.label = e.displayName;
e.title = e.displayDetail;
e.type = map[e.inputType];
delete e.displayName;
delete e.displayDetail;
delete e.inputType;
}
console.log('after data...');
console.log(data);
return data;
};
Thanks
You are trying to push into an array at $scope.formFields which doesn't exist.
This works. http://plnkr.co/edit/p5niu38aWpN5BbIxcyZ0?p=preview
$scope.getFromAFile= function () {
// body...
var inputs=[];
$http.get('a.json').success (function(data){
var a=changeData(data);
console.log('pp');
console.log(data.studentName);
console.log($scope);
$scope.formFields = a['input'];
}).error(function(err){
alert(err);
});
}

Fetching Data using .getJSON and storing using Knockout.JS

My TweetModel is setup like this
function TweetModel(tweet) {
var self = this;
this.tweet = ko.observable(tweet);
}
[UPDATED]
Running into trouble binding the solution. For some reason, after the TweetModel object is created, it is not being pushed to self.tweets.
I broke this up into steps...
.getJSON(someurl, function(data){
$.each(data, function (i, val) {
var tweetModel = new TweetModel();
tweetModel.tweet = data.key[0];
self.tweets.push(tweetModel);
//all could be compressed into self.tweets.push(new TweetModel(val));
//Object is being created but self.tweets returns an empty list when debugged
}}
Any help would be appreciated, thanks.
Try this:
$.getJSON(someurl, function (data) {
$.each(data.key, function (i, val) {
self.tweets.push(new TweetModel(val));
}
}

Categories

Resources