2013-05-03 26 views
8

データベースに入力するために反復処理するオブジェクトの配列を格納するエンコードされたJSONオブジェクトがあります。Javascriptを使用してJSONオブジェクト内の配列内のオブジェクトにアクセスする

{ 
    "customers": [ 
     { 
      "customer": { 
       "id":"1", 
       "customerName":"Customer Alpha", 
       "customerID":" custA", 
       "customerAddress":" Alpha Way", 
       "customerCity":" Alpha", 
       "customerState":" AL", 
       "customerZip":"91605" 
      } 
     }, 
     { 
      "customer": { 
       "id":"2", 
       "customerName":"Customer Beta", 
       "customerID":" CustB", 
       "customerAddress":" Beta Street", 
       "customerCity":" Beta", 
       "customerState":" BE", 
       "customerZip":"91605" 
      } 
     } 
    ] 
} 

私はデータベースに各フィールドの入力にできるようにしたいと思いますが、私は入力を持っているコードはすべてのためのデータベースに未定義:Resultオブジェクトは、次のように似ています。配列内の各フィールドに格納されている変数にアクセスする適切な方法は何ですか?ここで

は、私は仕事しない、これまで使用してんだよ:

function insertCustomer(customerName, customerID, customerAddress, customerCity, customerState, customerZip) { 
db.transaction(function (tx) { 
    tx.executeSql('INSERT INTO Customers (customerName, customerID, customerAddress, customerCity, customerState, customerZip) VALUES (?, ?, ?, ?, ?, ?)', [customerName, customerID, customerAddress, customerCity, customerState, customerZip], CountReturns); 
    }); 
}; 

     $.ajax({ 
     url  : 'http://webserver/retrieveDatabase.php', 
     dataType : 'json', 
     type  : 'get', 
     success : function(Result){ 
     alert(Result.customers); 
     for (var i = 0, len = Result.customers.length; i < len; ++i) { 
      var customer = Result.customers[i]; 
      insertCustomer(customer.customerName, customer.customerID, customer.customerAddress, customer.customerCity, customer.customerState, customer.customerZip); 
     } 
     } 
    }); 

アラートは、[オブジェクトのオブジェクト]の一連ので応答します。

var customer = Result.customers[i].customer; 
+0

使用 'console.log'代わりの警告(およびため、ブラウザのコンソールをチェックします出力)。 'Result.customers'はオブジェクトの配列なので、警告はあなたが見ているものを示しています。 – bfavaretto

+1

上記のサンプルデータから、たとえば、顧客名が「Result.customers [i] .customer.customerName'」を使用してアクセスされるように見えます。あなたのコードは 'Result.customers [i] .customerName'のみを使用します。一時変数 'customer'の名前はこの微妙な部分を隠します。 –

+0

@JimCote、あなたの答えは "答え"ではないので、私はそれをバンプすることはできませんが、私の頭蓋骨を叩いて3日後、あなたのコメントは私を助けました! – BillyNair

答えて

7

変更

var customer = Result.customers[i]; 

次のようなJSONオブジェクトを扱うことができます。

for(var key in Result["customers"]) { 
    // examples 
    console.log(Result[key].customer); 
    console.log(Result[key]["customer"]); 
    console.log(Result[key]["customer"].customerID); 
} 
+0

ありがとうございました。できます! =) – EzAnalyst

1

関連する問題