循环JS列表项

时间:2017-11-27 00:41:04

标签: javascript json node.js

我正在提交一个api请求,返回这样的响应。

    //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...

我将此视为一个数组并试图像这样循环:

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

并且它返回undefined。我假设它是一个JSON列表,我尝试使用console.log(JSON.stringify(list [i]))没有运气。

编辑:这是我的整个调用,它正在检索列表,因为api会自动调用它。记录它。

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]);
})

1 个答案:

答案 0 :(得分:0)

这样做:

JSON.parse(list).forEach(function(obj, idx){
    console.log("Object " + idx, obj)
})