0

I am trying to add to an object in Node:

exports.getAthleteData = function(accessToken, athleteId) {
    var athleteData = {};
    strava.athlete.get({'access_token': accessToken},function(err, payload) {
        athleteData.push({
            athleteName: payload.firstname + ' ' + payload.lastname,
            profile: payload.profile,
            profileMedium: payload.profile_medium,
            isPremium: payload.premium,
            sex: payload.sex
        });
    });
    return athleteData;
}

When calling the function I get an error TypeError: athleteData.push is not a function.

If I remove .push and do the below, all that is returned is {}.

athleteData = {
                athleteName: payload.firstname + ' ' + payload.lastname,
                profile: payload.profile,
...

To be sure, I dumped payload in the console and it gave me the JSON object I was expecting.

I'm certainly missing something very simple. This is my first foray into Node/Express and I'm really enjoying it, but I need to improve my JavaScript after years of relying on jQuery.

3
  • 3
    athleteData is an object. Objects don't have a push method - did you mean to define it as an array? var athleteData = [] - I also worry that strava.athlete.get is an async method and you're returning before the call is complete. Commented Dec 31, 2015 at 17:13
  • athleteData is an object not an array ,it doesn't have a push() method. Commented Dec 31, 2015 at 17:15
  • Also, you cant return athleteData like that. strava.athlete.get is async, so you have to do a callback with athleteData. Commented Dec 31, 2015 at 17:18

1 Answer 1

2

push is an Array method. If you want athleteData to be an array, change its declaration: var athleteData = [];

It is possible to add new keys to an object dynamically using the bracket syntax, but you need to come up with the name of the key. for example:

var obj = {};
var funkyKey = '1234'
obj['name'] = 'Bob';
obj['age'] = 23;
obj[funkyKey] = 'test';
console.dir(obj); // { name: 'Bob', age: 23, 1234: 'test }

yes, this is similar to using the dot syntax: obj.name = 'Bob', but gives you more control over the name of the new key.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.