0

I am submitting an api request that returns a response like this.

    //Example Response
[
  {
"id": 34,
"user_id": 1,
"first_name": "Awesome",
"last_name": "Person",
"email": "awesome+person@paywhirl.com",
"phone": "4564564566",
"address": "123 Easy Street",
"city": "Los Angeles",
"state": "California",
"zip": "93003",
"country": "US",
"created_at": "2015-11-17 19:52:34",
"updated_at": "2015-11-21 04:29:45",
"gateway_reference": "783789y6r890",
"default_card": 34,
"gateway_type": "PayPal",
"gateway_id": 18,
"currency": "USD",
"deleted_at": null,
"utm_source": "",
"utm_medium": "",
"utm_term": "online payments",
"utm_content": "",
"utm_campaign": "",
"utm_group": "",
"metadata":""
  }, and so on...

I am treating this like an array and trying to loop through like this:

for(var i=0; i<list.length; i++) {
  console.log(list[i]);
}

and it's returning undefined. I'm assuming it's a JSON list, and I've tried using console.log(JSON.stringify(list[i])) with no luck.

EDIT: This is my entire call, and it is retrieving the list because the api automatically console.logs it.

paywhirl.Customers.getCustomers(null, function(err, pw_customers) {

// for each paywhirl customer...
for(var i=0; i<pw_customer.length; i++) {
    // get stripe customer with same gateway reference
    stripe.customers.retrieve(
      pw_customer[i].gateway_reference,
      function(err, stripe_customer) {
        // create user
        var user = new User({
            username: pw_customer[i].email,
            stripe_id: pw_customer[i].gateway_reference});
        count++;
      }
    );
}

console.log(pw_customers[0]);
})
David
  • 944
  • 1
  • 13
  • 20
  • 1
    Please show more code context. You are probably trying to access the data before it has been received – charlietfl Nov 27 '17 at 00:43
  • what does `console.log(JSON.stringify(list, null, 2))` print out? – vicatcu Nov 27 '17 at 00:44
  • Where you have list[i], that is the object itself. console.log the values in the object you would just do list[i].id list[i].user_id etc. etc. within each loop. – SynchroDynamic Nov 27 '17 at 00:45
  • `stripe.customers.retrieve()` is asynchronous. Also you do nothing with `var user`. Also `i` is not going to be what you think it is when those requests do complete...it will be at it's maximum by then. Will need to create an array of promises and resolve that array before you can move on – charlietfl Nov 27 '17 at 00:59
  • Related: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) .. and... [JavaScript closure inside loops - simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – charlietfl Nov 27 '17 at 01:02

1 Answers1

0

Do this:

JSON.parse(list).forEach(function(obj, idx){
    console.log("Object " + idx, obj)
})
mikeb
  • 10,578
  • 7
  • 62
  • 120