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

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);
});
}

Related

javascript array.map function not working

I am using laravel and vuejs to create a chat app. I have encrypted my response in laravel by doing like this as I do not want anyone to see my response in console also:-
public function get()
{
$contacts = User::where('id', '!=', auth()->id())->get();
$unreadIds = Message::select(\DB::raw('`from` as sender_id,count(`from`) as messages_count'))
->where('to', auth()->id())
->where('read', false)
->groupBy('from')
->get();
$contacts = $contacts->map(function($contact) use ($unreadIds) {
$contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
$contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
return $contact;
});
$contacts = base64_encode($contacts);
return response()->json($contacts);
}
Now when I wish to access this value to display data in vue js, I am doing something like this:-
axios.get(this.globalUrl+'/contacts')
.then((response) => {
let encryptData = atob(response.data);
console.log(encryptData);
//data received after de-converting
/*[{"id":2,"phone":null,"name":"Casimir Morar MD","email":"clint.haag#hartmann.info","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":3,"phone":null,"name":"Lina Prosacco","email":"okeefe.camila#gmail.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":4,"phone":null,"name":"Miss Aglae Emard DDS","email":"qcarter#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":5,"phone":null,"name":"Demarco Kilback","email":"kessler.coy#swift.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":6,"phone":null,"name":"Tyrell Ziemann Sr.","email":"clementina.kautzer#price.org","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":7,"phone":null,"name":"Ella Hand","email":"areichel#watsica.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":8,"phone":null,"name":"Dr. Maxie O'Hara DDS","email":"wallace31#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":9,"phone":null,"name":"Mrs. Mattie Monahan IV","email":"ernser.pasquale#hotmail.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":10,"phone":null,"name":"Bradly Crona","email":"lehner.cordie#pagac.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0},{"id":11,"phone":null,"name":"Orland Kihn","email":"jacobs.wyman#yahoo.com","profile_image":null,"created_at":null,"updated_at":null,"unread":0}]*/
let finalArray = encryptData.map(function (obj) {
return obj;
//this.contacts.push(obj);
});
console.log(finalArray);
this.contacts = finalArray;
});
Here I am getting the data in the encryptData variable as an array of objects but proceeding further, every time I am getting this error:-
Uncaught (in promise) TypeError: encryptData.map is not a function
Please help me in finding the solution thanks.
You're probably missing a JSON.parse call:
axios.get(this.globalUrl + '/contacts')
.then((response) => {
let encryptData = JSON.parse(atob(response.data));
let finalArray = encryptData.map(function(obj) {
// ...
});
this.contacts = finalArray;
});
Basically:
your PHP script returns the base64-encoded data, in JSON format,
axios.get's callback receives this as a base64-encoded string,
atob base64-decodes the string (it's still a string at this point),
JSON.parse transforms it back into the actual data.

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;

Populating array with nested $each functions and conditionals in Angular with jQuery

I'm having a json object I get from a get request in an angular application. It gives me two main attributes data and included. The included object is somehow a relationship with the data object. For example data shows messages and included the senders of those messages. I managed to associate every message with the sender by checking if an attribute from the data object is the same with another attribute in the included object. here is my code
$http.get('data.json').then(
function(jsonAPI) {
console.log(jsonAPI);
var dataObj = {};
var messages = [];
$.each(jsonAPI.data.data, function(x, data) {
dataObj[x] = data;
$.each(jsonAPI.data.included, function(y, included) {
if (data.relationships.sender.data.id == included.id) {
dataObj[x].sender = included;
}
});
messages.push(dataObj[x]);
});
$scope.newMessages = messages;
},
function(errorResponse) {
// todo handle error.
}
);
I create a new array that contains all the data object and also sender's information under the sender attribute. The problem is that a new relationship is added called user_data_template. I want with a similar way to be able to pass to the messages array the corresponding user_data_template data. How can I change the above nested $each function to achieve that?
Here is a working plunker
I managed to find the solution. I had to change the code to the following:
$.each(jsonAPI.data.data, function(x, data) {
dataObj[x] = data;
$.each(jsonAPI.data.included, function(y, included) {
if(data.relationships.sender.data.id == included.id && included.type == "user") {
dataObj[x].sender = included;
}
if(data.relationships.user_data_template.data !== undefined) {
if(data.relationships.user_data_template.data.id == included.id && included.type == "user_data_template") {
dataObj[x].question = included;
}
}
});
messages.push(dataObj[x]);
});
And the new plunker

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);
});
};

parsing json array in javascript with unknown field names

I have found a lot of threads here on StackOverflow that talk about parsing json arrays but I can't seem to figure out how to get back some of the data. Here is what I have...
$('#keyword_form').submit(function(e){
var gj = $.post('employee_search.php',$('#keyword_form').serialize(),function(data){
if(!data || data.status !=1 )
{
alert(data.message);
return false;
}
else
{
alert(data.message);
}
},'json');
e.preventDefault();
});
The json data being sent to it looks like this...
{
"status":1,
"message":"Query executed in 9.946837 seconds.",
"usernames_count":{
"gjrowe":5,
"alisonrowe":4,
"bob":"1"
}
}
As my function shows I can do alert(data.message); but how can I access the usernames_count data?
My confusion comes from the fact that the data has no name/label. bob is a username and 1 is the returned count associated with that username
If I do alert(usernames_count); I get back [object Object]
If I do alert(usernames_count[0]); I get back undefined
I am sure I should be doing something with JSON.parse(); but I haven't gotten it right yet
You can use Object.keys or a for…in loop – remember in that case to use hasOwnProperty:
var users = data.usernames_count;
Object.keys(users).forEach(function(user) {
console.log(user, users[user]);
});
Try this:
$.each(data.usernames_count, function(username, val) {
alert(username+" has a value of "+val);
});
It sounds like your question is how to iterate over the entries in the usernames_count object. You can do that like so:
var key = '';
for(key in data.usernames_count) {
//check that this key isn't added from the prototype
if(data.usernames_count.hasOwnProperty(key) {
var value = data.usernames_count[key];
//do something with the key and value
}
}

Categories

Resources