You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历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

  1. 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).
  2. Feed the right data to DataTable: Instead of passing the whole product object, use the transformed array we just created as the data source.
  3. 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) for inventoryRows—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 invSelectionCount object.
  • Data Parsing: Object.entries() lets us loop through both keys and values of the nested object, and split() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:03:13