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

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

Related

Beacon prefill function

I already set up the Beacon 'identify' stuffs, and can open up using Beacon("open");
But when I try to use prefill function, i'm getting some error.
Beacon("prefill", {
name: "Steve Aoki",
email: "steve#aoki.com",
subject: "Need help with invoice",
text: "Hello, I need some help with my invoice. See attached.."
})
Error: Uncaught TypeError: Cannot read property 'filter' of undefined
Any code that I missed? Thanks in advance.
Reference here
You need to have a fields array, because in the example you posted, the one thing your code doesn't have is a fields array. This is also shown because filter is an array method, and calling fields.filter when you don't have fields will result in an undefined error.

Console log JSON result

I'm just starting to learn about APIs, JSON, and Jquery and I am stuck. How would I console log the following from my Jquery call -
name: "The Old Mill Cafe"
Here's my current code:
$(document).ready(function(){
$("#mainbutton").on("click", function() {
$.ajax({
url: "https://developers.zomato.com/api/v2.1/search?entity_id=Chicago%2C%20IL%20&entity_type=city",
headers: {
"X-Zomato-API-Key": "…"
},
method: "GET"
}).done(function(data) {
console.log(data);
});
});
});
Your console.log is telling you that data is an object with a property called restaurants which is an array with a single entry. That entry is an object with a property called restaurant which is an object with a property called name. So:
console.log(data.restaurants[0].restaurant.name);
In this case you are getting list of restaurants which has attributes like name and so on.
To get one restaurant you have to get first element of data
data[0] this will give you first restaurant of the list.
Now you need to get the name of the first restaurant to do that
data[0].name
So to get the name of the first restaurant you have to use following
console.log(data[0].name);

How to get values from this data structure

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

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.

Mongoose, resolve path in embedded array

I have the following Mongoose schema:
var WeekSchema = new Schema({
days: [{
name: String
}]
});
and I want to get 'name' and do something with it (lets assume a validation).
So, I try to validate using the following code:
WeekSchema.path('days.name').validate(function(value){
return /monday|tuesday|wednesday|thursday|friday|saturday|sunday/i.test(value);
}, 'Invalid day');
but i get the error:
WeekSchema.path('days.name').validate(function(value){
^
TypeError: Cannot call method 'validate' of undefined
in fact if I print the resolved path with
console.log(WeekSchema.path('days.name'));
I have 'undefined'.
The question is, how can I get 'name' by using its path?
I met this issue today so I did a little research by printing out the main path, in your case: console.log(JSON.stringify(WeekSchema.path('days'), null, 4)); Then I figured out the path to the sub docs to be:
WeekSchema.path('days').schema.path('name');
This is my first answer here, hope it helps :)

Categories

Resources