How to get values from this data structure - javascript

An ajax request (stored in a variable named results) is returning this data as a response:
Object {hits: Object, links: Object}
hits:Object
hits:Array(2)
0:Object
active:true
email:"user1#example.com"
id:1
links:Object
__proto__:Object
1:Object
active:true
email:"user2#example.com"
id:2
links:Object
__proto__:Object
length:2
__proto__:Array(0)
total:2
__proto__:Object
links:Object
__proto__:Object
What sort of data type it has? I thought it is json but using JSON.parse(results) returns this error:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
How can I get access to the Array inside it? I need to get the email addresses and ids. It's probably not relevant but I'm using it in a ReactJS component.

According your response, it's already a JSON object.
So if you want to access the hits property, here is the code: results.hits.
Also you mentioned the following:
It recognizes the first hits, but not the second one.
Can you please try to console.log(results.hits) and share the output here? I guess your response object has only one hits property and it's type is array.

Observation : As response is already a JSON Object so no need to Parse it again.
Suggestion : Use array.map() method to iterate the array and fetch the required elements.
DEMO
var results = {
"hits": {
"hits": [
{
active:true,
email:"user1#example.com",
id:1
},
{
active:true,
email:"user2#example.com",
id:2
}
]
},
"links": {}
};
var res = results.hits.hits.map(function(item) {
return item.email;
});
console.log(res);

Related

Parsing a URL query object in node.js

I need to create a function that will use an object passed in the url. The goal is to update menu items for a restaurant. The query sent will look like this:
?restId=1&posId=1&groups=…&items= [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]&pizzas=[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]
When I run const queryObject = url.parse(req.url,true).query; it prints:
[Object: null prototype] {
restId: '1',
posId: '1',
groups: '…',
items: ' [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]',
pizzas: '[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]'
}
My problem is that I cannot access any of the values in items. I was given this url, so I cannot change it at all. How can I parse items in order to access the values?
The value of items and pizzas are both JSON formatted strings. You have to parse them to access the contained data. This is accomplished by calling JSON.parse()
So in your case, to access items, you could do the following:
const items = JSON.parse(queryObject.items)
The only problem you have now is that items isn't actually a valid JSON string. It's missing four closing tags }]}] at the end. I'm not sure if that's a transcription error or if you're actually getting a malformed URL, but that will cause you issues if the URL in your question is accurate.

JSON : Cannot read property 'value of a key' of undefined

So, Im trying to deal with an API.
i successful load the json(which is an array of objects) in my browser like the following
0:
source: {id: null, name: "Protothema.uk"}
author: "james bond"
title: " A TITLE"
description: "A DESCRIPTION"
__proto__: Object
my code
$.getJSON("http://newsapi.org/v2/top-headlines?country=uk&category=health&apiKey=MYAPIKEY", function(data){
//console.log(data);
$.each(data,function(index,value){
console.log(value);
console.log(value[0]);
console.log(value[0].title)//Cannot read property 'title' of undefined
});
});
when i try to print the whole index like console.log(value[0]); i successfully get all the objects of the index 0.
but when i try to print a specific value of key like console.log(value[0].title) i get Cannot read property 'title' of undefined
im stuck for hours, what im doing wrong?
Structure of Response data:
Based on the structure, try access title of every article:
// Using JQuery.each()
$.each(data.articles,function(index, article){
console.log(article.title); // to access title of each article.
});

How to get value out of Observable Array nested object

I have searched here for an answer to this question with no luck.
I have an observable array which contains only one entry:
I have it stored in self.user()
POSData.Users.getByEmail(sEmail)
.then(data => {
//console.log(data)
self.user.push(data);
})
Now I simply want to extract a few values and assign them to their own observables, BUT... I can't.
I have tried the following to get the firstName...
console.dir(self.user());
//console.log(self.user()[0].data.firstName());
//console.log(self.user().firstName());
//console.log(self.user().data.firstName());
//console.log(self.user()[0].data.firstName());
//console.log(self.user().data[1].firstName());
Does anyone know how to drill down and get to the information I want?
Thanks for looking.
John
You're storing the raw data you got back from your service into your array. You should access members of that data in that form. The firstName property is not an observable, it's just a string in the data property so you shouldn't be calling it as if it was an observable. The only observable in your example is apparently self.user.
Based on your screenshot your new data looks something like this:
{
data: {
firstName: 'John',
lastName: 'Smith'
},
message: 'User retrieved successfully',
status: null
}
If you want to get the first name of this object in your user array, you'd access it like this:
self.user()[0].data.firstName

get JSON object javascript

I have the Student.groovy class that hasMany Note.groovy
Student Class extend to User.groovy
I have a JavaScript function that takes as a parameter a list of notes in JSON.
The code below works.
$.each(data,function(key, value) {
alert(value.note);
alert(value.semester)
});
But if I do alert(value.student); me is returned [object, object]
and when I put alert(value.student.toSource()); It's shown ({class: "project.Student", id: 1})
If I do alert(value.student.name); It's shown undefined
You're most likely not sending back the correct JSON format to access the student's name.
As of now with the examples you have given you can only access the class and id of a given student.
value.student.class //<-- project.student
value.student.id //<-- 1
To be able to access the student's name you would have to have an object like so:
{
class: "project.Student",
id: 1,
name: "Example name"
}
If you think you are actually sending everything you need from the server just do a little $(document.body).append(data); or console.log(data); on your getJSON success callback so you can see clearly what you have.
I wouldn't be surpized if value.name works by the way. Depends on your json structure.

Parse JSON response store value in variable

I'm getting the following JSON response:
"Nitro": {
"Login": {
"sessionKey": "NHwxNDQ4MzR8MzY1ODE5ODMwMnwxMzQ0NzE5MTYyfDgxY2M1NjYxZDBiY2NiODI4NmM2Mjc1ODI2MzA1NDY3YmVhNzJjZDR8MA=="
},
"res": "ok",
"method": "user.login",
"server": "sbnitro01.prod.bunchball.net/nitro4.4.0"
}
}
I don't understand how to parse this with JavaScript and store the value of the sessionKey in a variable. I cannot use jQuery on this project and just cannot seem to get the key with JS.
Thanks!
Try:
var sessionKey = obj.Nitro.Login['sessionKey'];
This takes the object that is stored in the obj variable, then takes the Nitro property object and then takes the Login property object and extracts the property sessionKey accordingly.

Categories

Resources