Javascript + JQuery: Object properties are undefined [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to build a simple web app using JQuery. I'm trying to make an ajax request to the server the following way:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
I also do the following:
$(document).ready(function() {
console.log(getClients());
});
So that I can see the result of my request. In the console I see the following:
{
"readyState": 4,
"responseText": "{\"count\":2,\"next\":null,\"previous\":null,\"results\":[{\"id\":2,\"group_set\":[1],\"first_name\":\"b\",\"last_name\":\"b\",\"username\":\"b\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null},{\"id\":1,\"group_set\":[1],\"first_name\":\"a\",\"last_name\":\"a\",\"username\":\"a\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null}]}",
"responseJSON": {
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 2,
"group_set": [
1
],
"first_name": "b",
"last_name": "b",
"username": "b",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
},
{
"id": 1,
"group_set": [
1
],
"first_name": "a",
"last_name": "a",
"username": "a",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
}
]
},
"status": 200,
"statusText": "OK"
}
(This output is made by clicking on "Copy object" in Firefox).
However, if I change getClients() as shown below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
}).responseJSON;
}
Then in the console I will get
undefined
Also, when I try to use the object's properties in code, I get an error that the properties are undefined.
How is that and how do I fix this?
Thank you.

getClients returns promise. Your code:
return $.ajax(...).responseJSON
reads responseJSON from promise object which is undefined. Promise returns result only when it is resolved (then())
You should leave getClients as is and change part in document ready like:
$(document).ready(function() {
getClients().then(function(response) {
const respJson = JSON.parse(response);
console.log(respJson.responseJSON);
});
})

Keep the getClients() function as seen below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
Then use Bracket Notation to select properties:
var clientData = getClients();
var jsonData = clientData["responseJSON"];
var results = jsonData["results"];
console.log(results[0]["first_name"]); // Logs the "first_name" value from first results array
Since your JSON properties are strings, Bracket Notation is required. Otherwise, you could use, for example: clientData.responseJSON

Related

How to create a json object from another json object using JavaScript?

I am really junior with JavaScript and json, so I have this JSON input, and I need to get all that information in the "properties" object to create a new JSON object with just that information.
I'm using a base code like this one, but this is just returning {}.
exports.step = function(input, fileInput) {
var alert = {
'Properties': input.alert.properties
}
return JSON.stringify(alert, undefined, 1);
};
Original JSON:
"value": {
"id": "12345",
"entity": {
"_integrationDefinitionId": "7a6764",
"_integrationName": "Apple Main",
"_beginOn": "2021-09-01T02:20:06.189Z",
"displayName": "apple-onev",
"_accountIdPartitioned": "12345|12",
"_class": [
"Deployment",
"Group"
],
"_version": 3,
"_integrationClass": [
"CiSSP",
"Infrastructure"
],
"_accountId": "123456",
"_id": "1e234567",
"_key": "arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456",
"_type": [
"aws_autoscaling_group"
],
"_deleted": false,
"_rawDataHashes": "1233456==",
"_integrationInstanceId": "54321",
"_integrationType": "aws",
"_source": "integration",
"_createdOn": "2021-07-19T23:19:19.758Z"
},
"properties": {
"webLink": "https://google.com",
"arn": "name",
"region": "us-west-2",
"name": "JonnyAndTheVibes",
"launchConfigurationName": "OtherName",
"minSize": 1,
"maxSize": 4,
"desiredCapacity": 1,
"defaultCooldown": 360,
"availabilityZones": "us-west-2a",
"LoadBalancerNames": "MoreInfo",
"healthCheckType": "EC2",
"healthCheckGracePeriod": 0,
"instanceIds": "InstanceName",
"subnetIds": "subnet",
"terminationPolicies": "Default",
"newInstancesProtectedFromScaleIn": false,
"serviceLinkedRoleARN": "aMoreInfo",
"tag.Name": "atag",
"tag.application": "othertag",
"tag.aws:cloudformation:logical-id": "moretagsp",
"tag.aws:cloudformation:stack-id": "taggigante",
"tag.aws:cloudformation:stack-name": "ydaleconlostags",
"tag.elasticbeanstalk:environment-id": "seguimosmetiendoletags",
"tag.elasticbeanstalk:environment-name": "tag",
"tag.env": "tag",
"tag.team": "tag",
"accountId": "tag",
"tag.AccountName": "tag",
"tag.Production": true,
"#tag.Production": "​"
}
}
I'm sure that it will be a simple solution.
You appear to be trying to grab properties from the wrong object. It should be value not alert.
const json = '{"value":{"id":"12345","entity":{"_integrationDefinitionId":"7a6764","_integrationName":"Apple Main","_beginOn":"2021-09-01T02:20:06.189Z","displayName":"apple-onev","_accountIdPartitioned":"12345|12","_class":["Deployment","Group"],"_version":3,"_integrationClass":["CiSSP","Infrastructure"],"_accountId":"123456","_id":"1e234567","_key":"arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456","_type":["aws_autoscaling_group"],"_deleted":false,"_rawDataHashes":"1233456==","_integrationInstanceId":"54321","_integrationType":"aws","_source":"integration","_createdOn":"2021-07-19T23:19:19.758Z"},"properties":{"webLink":"https://google.com","arn":"name","region":"us-west-2","name":"JonnyAndTheVibes","launchConfigurationName":"OtherName","minSize":1,"maxSize":4,"desiredCapacity":1,"defaultCooldown":360,"availabilityZones":"us-west-2a","LoadBalancerNames":"MoreInfo","healthCheckType":"EC2","healthCheckGracePeriod":0,"instanceIds":"InstanceName","subnetIds":"subnet","terminationPolicies":"Default","newInstancesProtectedFromScaleIn":false,"serviceLinkedRoleARN":"aMoreInfo","tag.Name":"atag","tag.application":"othertag","tag.aws:cloudformation:logical-id":"moretagsp","tag.aws:cloudformation:stack-id":"taggigante","tag.aws:cloudformation:stack-name":"ydaleconlostags","tag.elasticbeanstalk:environment-id":"seguimosmetiendoletags","tag.elasticbeanstalk:environment-name":"tag","tag.env":"tag","tag.team":"tag","accountId":"tag","tag.AccountName":"tag","tag.Production":true,"#tag.Production":"​"}}}';
function getAlert(dsta) {
// Destructure the properties object from the
// data's value property
const { properties } = data.value;
// Create a new object with it
const alert = { properties };
// Return the string
return JSON.stringify(alert, null, 2);
};
// Parse the JSON
const data = JSON.parse(json);
// Call the function with the parsed data
const alert = getAlert(data);
console.log(alert);
Additional information
Destructuring assignment
use this function :
function assignJsons(...jsons) {
const convertToObject = jsons.map(json => {
return JSON.parse(json)
});
return JSON.stringify(Object.assign(...convertToObject))
}
//test
console.log(assignJsons(`{"name" : "alex", "family" : "mask"}`, `{"family" : "rejest"}`))
if you want a completely new object
var newJsonObject = JSON.parse('{ "properties":'
+ JSON.stringify (origJson.value.properties) + "}");
or
var newJsonObject={"properties":Object.assign ({}, origJson.value.properties)};

How to retrieve value in javascript

I am returning a json as shown below,
{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}
I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];
When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];
When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;
What I am missing here, couldn't find same kind of question
Why stringify and parse?
Anyway, it is more complex than you think
const obj = JSON.parse(str)
console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>
I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
Object.values(response.entities.permissions).forEach(element => {
permissionIds.push(element.id)
});
var userIds=[];
Object.values(response.entities.users).forEach(element => {
userIds.push(element.id)
});

How do I pass a request parameter from a URL to a function that returns an object of the same name in JavaScript?

I want to pass a request parameter from an express router request to a function that will return an object of the same name, however the function returns the parameter name.
I've looked at the typeof the function parameter and it's type 'object' however req.params returns type string. How do i circumvent this?
router.get('/about/:place', (req, res) => {
// the object
Mombasa = {
"Destination": "Mombasa",
"Price": 12000,
"Likes": 0,
"Gallery": [{
"image": "https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"
}, {
"image": "https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"
}]
};
// function that returns the object
getPlace = (placeName) => {
return placeName;
}
// trying to send reaponse of whole object
res.json(getPlace(req.params.place));
});
expected result:
{"Destination":"Mombasa","Price":12000,"Likes":0,"Gallery":[{"image":"https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"},{"image":"https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"}]}
actual result:
"Mombasa"
I think you might want to have a parent object for your Mombasa object so you can use property keys to get the desired object like this:
const myObjects = {
Mombasa: {
"Destination": "Mombasa",
"Price": 12000,
"Likes": 0,
"Gallery": [{
"image": "https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"
}, {
"image": "https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"
}]
}
};
Then you can get this object by using the key "Mombasa":
getPlace = (placeName) => {
return myObjects[placeName];
}
Your Object must be like following,
and also move the methods and object outside of router.
router.get('/about/:place', (req, res) => {
// trying to send reaponse of whole object
res.json(getPlace(req.params.place));
});
let obj = {
Mombasa: {
"Destination": "Mombasa",
"Price": 12000,
"Likes": 0,
"Gallery": [{
"image": "https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"
}, {
"image": "https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"
}]
}
}
// function that returns the object
getPlace = (placeName) => {
return obj[placeName];
}

angularjs: Push is not a function

I have a JSON object like this:
var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};
And post is passed to the function given below from the front end.
var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here
myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};
But doing so, I get a JavaScript error saying push is not a function in line likedPost.likers.push(userObject);
And userObject is returned by vm.userInfo() and it looks like this:
vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};
and the returned JSON is like this:
{"id":"12","firstName":"Amelia","lastName":"Earheart"}
Can anyone help me figure out the cause of this issue?
UPDATE:
{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}
This is what I get upon console.log(likedPost);
The output clearly specifies that likers is not defined. You can put a validation check before using push() method.
//if likedPost.likers is not defined, it will define it as an array
likedPost.likers = likedPost.likers || [];
//Do the push operation
likedPost.likers.push(userObject);
Your likedPost object doesn't have the likers array you expect. Probably you can see if that exists before trying to push.
if (typeof likedPost !== 'undefined')
likedPost.likers.push(userObject);

Read API response in Angular2 & ionic

I have successfully get it work to request data from API with http.get in Angular2. This is my http.get
this.http.get('http://localhost:8001/v1/recent', {
headers: headers
})
.map(res => res.text())
.subscribe(
data => console.log(data.total),
() => console.log('API request complete')
);
The API is based on Laravel, it will return data as follows
{
"total": 8,
"per_page": 50,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 8,
"data": [
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
},
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
}
]
}
How can I retrieve the JSON object above in Angular2? and all of it's nested array?
console.log(data.total) above is return undefined
The json in your question is not properly formatted, you have an extra comma after "isBlocked":"0" (in line 15 and in line 22)
"author": {
"isBlocked": "0",
}
which will make it a invalid JSON. Preventing Angular from parsing it correctly.
The other issue, you are calling .map(res => res.text()) which will convert your response body to a string not an object. If you want it as a javascript object do .map(res => res.json()) instead.
Here is a working plunker

Categories

Resources