Friday, January 20, 2017

Javascript array is not accessible as an array

Leave a Comment

I'm working with the twitter API and I'm hitting a really confusing issue.

I have the following script:

const Twitter = require('twitter-api-stream') const twitterCredentials = require('./credentials').twitter  const twitterApi = new Twitter(twitterCredentials.consumerKey, twitterCredentials.consumerSecret, function(){     console.log(arguments) })  twitterApi.getUsersTweets('everycolorbot', 1, twitterCredentials.accessToken, twitterCredentials.accessTokenSecret, (error, result) => {     if (error) {         console.error(error)     }     if (result) {         console.log(result) // outputs an array of json objects         console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)         console.log(result[0]) // outputs a opening bracket ('[')         console.log(result[0].text) // outputs undefined     } }) 

Which is calling the following function to interact with twitter:

TwitterApi.prototype.getUsersTweets = function (screenName, statusCount, userAccessToken, userRefreshToken,cb ) {     var count = statusCount || 10;     var screenName = screenName || "";      _oauth.get(         "https://api.twitter.com/1.1/statuses/user_timeline.json?count=" + count + "&screen_name=" + screenName         , userAccessToken         , userRefreshToken         , cb     ); }; 

It seems like I'm getting the result I want. When I log the result itself I get the following output:

[   {     "created_at": "Thu Sep 01 13:31:23 +0000 2016",     "id": 771339671632838656,     "id_str": "771339671632838656",     "text": "0xe07732",     "truncated": false,     ...   } ] 

Which is great, an array of the tweets limited to 1 tweet.

The problem I'm running into is when I try to access this array.

console.log(result.length) //outputs 3506 for some reason (it's only an array of 1) console.log(result[0]) // outputs a opening bracket ('[') console.log(result[0].text) // outputs undefined 

I read back through the api docs for the user_timeline but unless I'm completely missing it I'm not seeing any mention of special output.

Any ideas?

Update

Thanks @nicematt for pointing out that answer.

Just to elaborate on the solution, I updated my code to this and now I'm getting the result I want:

if (result) {     let tweet = JSON.parse(result)[0] // parses the json and returns the first index     console.log(tweet.text) // outputs '0xe07732' } 

Thanks for the help!

1 Answers

Answers 1

Result is a String and you're indexing it (result[0] (whereas 0 is converted to a string), is almost identical to result.charAt(0) though), this is why result[0] is equal to "["–because it's the first character specified in. You forgot to parse the result as JSON data.

JSON.parse(result).length // probably 1 

And result.text is undefined since result (a string) is like an Object (but isn't instanceof) and allow lookups and getters to happen in itself.

I'd show the difference between str[0] and str.charAt(0), too:

str[0] // same as str['0'], but a getter. 0 converts to        // string (because every key of an object        // is string in ECMAScript)  str.charAt(0) // get/lookup String#charAt, call it               // without new `this` context and with arguments list: 0 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment