Reputation: 380
So I'm trying to grab some data from a json object through a for in loop and it keeps returning undefined. Here is my code:
router.get('/', function(req, res, next) {
request('https://api.instagram.com/v1/media/popular?client_id=############', function (error, response, body) {
json = JSON.parse(body);
var popular_tags = [];
for (var key in json['data']){
tag = JSON.stringify(key['tags'])
popular_tags.push(tag)
}
console.log(popular_tags)
res.render('index', {title: body });
});
});
This is the output I recieve:
[ undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined ]
However, when I try
var popular_tags = [];
popular_tags.push(json['data'][0]['tags'])
console.log(popular_tags)
It will print out what I want. Any suggestions?
Upvotes: 0
Views: 344
Reputation: 198466
When you say
for (var key in json['data'])
the key
is iterating through the attribute names of the object json.data
, and is thus a string. Thus, key['tags']
is undefined
as strings generally don't have an attribute tags
. Things snowball from there.
The general idiom is:
for (var key in json.data) {
if (json.data.hasOwnProperty(key) {
var item = json.data[key];
// ...
}
}
The hasOwnProperty
thing is the protection against someone injecting something in a prototype of whatever you're iterating. For example, if someone did something silly like Object.prototype.breakAllCode = true
, "breakAllCode"
would show up as a key
on whatever you were iterating.
Upvotes: 1
Reputation: 54543
Change the line to
tag = JSON.stringify(json['data'][key]['tags'])
Upvotes: 1