Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array is not accessible as an array

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!

like image 248
Chris Schmitz Avatar asked Sep 01 '16 14:09

Chris Schmitz


People also ask

Can I put an array in an array JavaScript?

Introduction to JavaScript multidimensional arrayJavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array.

Can you set an array equal to another array in JavaScript?

Yes you can do that.

Why is JavaScript array undefined?

Undefined value primitive value is used when a variable has not been assigned a value. The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.

Can an array be a VAR?

var array = new type[counter]; However, you cannot create a var array, as var is not a type, but a keyword used in place of a type, like C++11s auto. You will have to define a specific type for your array or you will hit problems. For your case, you need a dynamic or object array.


1 Answers

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
like image 151
Klaider Avatar answered Sep 30 '22 23:09

Klaider