Reputation: 10580
I have the following request call in my node.js app
request({ url:chanURL, qs:chanProperties}, function(err, response, body) {
if(err) { console.log(err); return; }
body = JSON.parse(body);
(function (body) {
Object.keys(body.items).forEach(function(item) {
pid = item.contentDetails.relatedPlaylists.uploads;
console.log(pid);
})
})();
})
And, I'm getting TypeError: Cannot read property 'items' of undefined
while processing the response.
The JSON object that I'm trying to work with is
{ kind: 'youtube#channelListResponse',
etag: '"0KG1mRN7bm3nResDPKHQZpg5-do/B7stMlWJTBpmW2q34yWKIzz8fF8"',
pageInfo: { totalResults: 1, resultsPerPage: 1 },
items:
[ { kind: 'youtube#channel',
etag: '"0KG1mRN7bm3nResDPKHQZpg5-do/vV2FFZUI5inz53NuQDJMTs3tdQk"',
id: 'UCwy6X3JB24VTsDFqMwdO5Jg',
contentDetails: [Object] } ] }
Why does it say items
is undefined?
And I also would like to know if I want to execute the function within this request wrapper, I need to wrap it inside the parenthesis like I did? I did get syntax error without the parenthesis.
Upvotes: 0
Views: 879
Reputation: 30340
There are a few problems with your code:
(function (body) { /* ... */ })()
You're calling the anonymous function without an argument. body
is therefore undefined
inside the function. You should omit the IIFE - it doesn't help you here.
Object.keys(body.items)
Object.keys
returns an array of the property names for an Object. body.items
is an Array, so you don't need to use it - you should iterate over the object directly.
pid = item.contentDetails.relatedPlaylists.uploads
contentDetails
is an Array. If you mean to use the first element, your code should read: item.contentDetails[0].relatedPlaylists.uploads
Making those changes leaves you with:
request({ url:chanURL, qs:chanProperties}, function(err, response, body) {
if(err) { console.log(err); return; }
body = JSON.parse(body);
body.items.forEach(function(item) {
pid = item.contentDetails[0].relatedPlaylists.uploads;
console.log(pid);
})
})
Upvotes: 3