2017-01-27 26 views
0

を慰めるためのエントリを選択したログI、各顧客の名前、ID、口座番号、アドレスを持ち、アカウント情報の配列と呼ばれる顧客を持っている:今、私は反復しようとしているため配列を反復処理し、

var customers = [ 
    { 
     "name": "John Doe", 
     "id": 1205, 
     "accountNumber": 187456, 
     "address": { 
      "houseNumber": 12, 
      "streetName": "made up street", 
      "postCode": "WE1 234", 
      "area": "Birmingham" 
     }, 
     "hasCurrentAccount": true, 
     "hasLoan": false, 
     "hasMortgage": true 
    }, 
    { 
     "name": "Jane Doe", 
     "id": 1304, 
     "accountNumber": 123456, 
     "address": { 
      "houseNumber": 420, 
      "streetName": "The Street", 
      "postCode": "DE3 456", 
      "area": "Wolverhampton" 
     }, 
     "hasCurrentAccount": false, 
     "hasLoan": true, 
     "hasMortgage": false 
    } 
]; 

この配列によって名前とIDを取得し、コンソールにそれを印刷:

var info = customers; 
for (var i in info) 
{ 
    var id = info.id; 
    var name = info.name; 
    console.log('Here are your current customers' + id + ' ' + name); 
} 

が、私はちょうど得る

Here are your current customers undefined undefined 

私はさまざまな方法を試みましたが、私はそれを動作させるように見えません。 誰も助けることができますか?

+0

あなたの例にはJSONはありません。オブジェクトの(JavaScript)配列のみ。ヒント: 'for(var i in info)'を使っていますが、 'i'で何もしません。 –

+0

私はもともとJSONを使用していたが、配列に変更したことに注意してください。 今すぐ編集します。 –

+0

'var id = i.id;' – nicovank

答えて

0

Array.forEach関数を使用して配列を反復処理できます。 これは、項目からコンソールに値を記録できる各項目で機能を実行します。

例:

var customers = [ 
 
    { 
 
     "name": "John Doe", 
 
     "id": 1205, 
 
     "accountNumber": 187456, 
 
     "address": { 
 
      "houseNumber": 12, 
 
      "streetName": "made up street", 
 
      "postCode": "WE1 234", 
 
      "area": "Birmingham" 
 
     }, 
 
     "hasCurrentAccount": true, 
 
     "hasLoan": false, 
 
     "hasMortgage": true 
 
    }, 
 
    { 
 
     "name": "Jane Doe", 
 
     "id": 1304, 
 
     "accountNumber": 123456, 
 
     "address": { 
 
      "houseNumber": 420, 
 
      "streetName": "The Street", 
 
      "postCode": "DE3 456", 
 
      "area": "Wolverhampton" 
 
     }, 
 
     "hasCurrentAccount": false, 
 
     "hasLoan": true, 
 
     "hasMortgage": false 
 
    } 
 
]; 
 

 
customers.forEach(function(item) { 
 
    console.log('Here are your current customers', item.id, item.name); 
 
})

+0

あなたの投稿は、問題の内容とその解決方法を説明すると、他の人にとってははるかに役立ちます。コードのみの回答は通常低品質とみなされます。 –

+0

フィードバックありがとう、 – Giladd

+0

@Giladdこれは魅力的です! 私は配列の各項目に対してこれを行うことができますか? –

0

これが問題を解決します。

for (a in customers){ 
console.log('Here are your current customers' + a + ' ' + customers[a].name); 
} 
+0

あなたの投稿は、問題の内容とその解決方法を説明すると、他の人にとってははるかに便利です。 * "これを試してください" *は単なる不要な文です。 –