如何用jQuery循环RajaOngkir数组数据并无重复追加至ComboBox
Got it, let's tackle this problem step by step. You want to take array data from RajaOngkir's API response, loop through it without duplicates, and append the options to a ComboBox using jQuery. Here's a practical, straightforward solution:
First, let’s align on the API structure: your sample response hints at a cost calculation request, so we’ll assume the target data lives in response.rajaongkir.results (the standard array RajaOngkir returns for courier/service details). We’ll focus on adding unique courier options first, then show how to adapt it for service types if needed.
Step 1: Prepare Your HTML ComboBox
Start with a basic select element in your markup—give it an ID so jQuery can target it easily:
<select id="courierComboBox" name="selectedCourier"> <option value="">Choose a Courier</option> </select>
Step 2: Fetch & Process Data with jQuery AJAX
Here’s the full code to call the API, filter duplicates, and build your ComboBox:
// Replace with your actual RajaOngkir API key and endpoint $.ajax({ url: "https://api.rajaongkir.com/starter/cost", method: "POST", data: { origin: "23", destination: "152", weight: 1500, courier: "all" }, headers: { "key": "YOUR_RAJAONGKIR_API_KEY" }, success: function(response) { // Verify the API returned a valid response if (response.rajaongkir.status.code === 200) { const comboBox = $("#courierComboBox"); const uniqueCouriers = new Set(); // Use Set to track already added items // Loop through each courier result from the API $.each(response.rajaongkir.results, function(_, courier) { const courierCode = courier.code; const courierName = courier.name; // Only add the option if it hasn't been added before if (!uniqueCouriers.has(courierCode)) { uniqueCouriers.add(courierCode); // Create and append the new option element const option = $("<option>") .val(courierCode) .text(`${courierName} (${courierCode})`); comboBox.append(option); } }); } else { console.error("API Error:", response.rajaongkir.status.description); } }, error: function(xhr, _, error) { console.error("AJAX Request Failed:", error); } });
Key Details:
- Duplicate Prevention: We use a
Setto track unique courier codes—this is cleaner and more efficient than checking an array withindexOf. - Dynamic Option Creation: We build jQuery
<option>elements on the fly, set their value (for form submission) and display text, then append them directly to the ComboBox. - Error Handling: We add checks for both API-level errors (like invalid credentials) and AJAX request failures to make debugging easier.
Adapt for Unique Service Types
If you want to append unique delivery services (e.g., "REGULAR", "EXPEDITE") instead of couriers, adjust the loop to iterate through each service under the courier’s costs array:
success: function(response) { if (response.rajaongkir.status.code === 200) { const serviceComboBox = $("#serviceComboBox"); const uniqueServices = new Set(); $.each(response.rajaongkir.results, function(_, courier) { // Loop through each service offered by the courier $.each(courier.costs, function(_, service) { const serviceCode = service.code; const serviceName = service.service; if (!uniqueServices.has(serviceCode)) { uniqueServices.add(serviceCode); const option = $("<option>") .val(serviceCode) .text(serviceName); serviceComboBox.append(option); } }); }); } }
Just add a corresponding <select id="serviceComboBox"> to your HTML for this use case.
内容的提问来源于stack exchange,提问作者HiDayurie Dave

