Доступ к объектам внутри массива внутри объекта JSON с помощью Javascript

у меня есть закодированный объект JSON, который хранит массив объектов, которые я хочу перебрать, чтобы ввести в базу данных. Объект Result аналогичен следующему:

{
    "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"
            }
        }
    ]
}

Я хотел бы иметь возможность вводить каждое поле в базу данных, но код, который я ввел, не определен в базу данных для всего. Каков правильный способ доступа к переменным, хранящимся в каждом поле внутри массива?

вот что я использую до сих пор, что не делает работа:

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

предупреждение отвечает серией [object Object] s.

2 ответов


изменить

var customer = Result.customers[i];

to

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

вы можете обрабатывать объект JSON, например:

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