如何遍历JSON对象,将invSelectionCount数据填充至含Color/Size/Quantity列的DataTable
How to Populate DataTable with Color/Size/Quantity from Nested JSON Key-Value Pairs
Got it, let's fix this up. The core issue right now is that your invSelectionCount is a key-value object, not the array format DataTable needs to populate columns directly. Each key combines color and size (like "red=small"), so we first need to parse those into separate, usable columns.
Here's how to adjust your code to make this work:
Step-by-Step Breakdown
- Transform the nested object: Loop through each key-value pair in
invSelectionCount. Split the key by=to separate color and size, then build a new object with the three columns we need (Color,Size,Quantity). - Feed the right data to DataTable: Instead of passing the whole product object, use the transformed array we just created as the data source.
- Map columns correctly: Update the column definitions to point to the properties of our transformed objects, not the raw nested object.
Modified AJAX Code
$.ajax({ url: 'http://localhost:8080/Retail-war/webresources/products/getProduct/' + productId, method: 'GET', contentType: 'application/json; charset=utf-8', headers: {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')}, }).done(function(data) { // Convert invSelectionCount into a DataTable-ready array const inventoryRows = Object.entries(data.invSelectionCount).map(([key, quantity]) => { // Split the combined key (e.g., "red=small") into color and size const [color, size] = key.split('='); return { Color: color.charAt(0).toUpperCase() + color.slice(1), // Optional: capitalize for readability Size: size.charAt(0).toUpperCase() + size.slice(1), Quantity: quantity }; }); // Initialize DataTable with our transformed data $('#product-inventory-level').DataTable({ data: inventoryRows, columns: [ { data: "Color", title: "Color" }, { data: "Size", title: "Size" }, { data: "Quantity", title: "Quantity" } ] }); })
Key Fixes from Your Original Code
- Data Source: We swapped
[data](which passed the whole product object) forinventoryRows—this is the array of row-specific objects DataTable expects. - Column Mapping: Each column now targets a clear property in our transformed objects, instead of all pointing to the raw
invSelectionCountobject. - Data Parsing:
Object.entries()lets us loop through both keys and values of the nested object, andsplit()breaks apart the combined color/size key into separate fields.
The capitalization step is optional—remove it if you want to keep the original lowercase values from the JSON.
内容的提问来源于stack exchange,提问作者Nic
相关产品推荐
相关产品推荐

