如何使用ReactJS展示服装类多维JSON数组数据
Got it, let's break down how to render your clothing inventory data in React exactly the way you want. You have a JSON object where each key is a product name, and the value is an array of size-quantity pairs—we'll turn that into clean, formatted output with a few simple steps.
Step 1: Set Up Your Component and Data
First, let's start with a basic functional component. I added some non-zero quantities to your sample data to make the output clearer:
import React from 'react'; const ClothingInventory = () => { // Your raw clothing data (replace with your actual data source) const clothingData = { "myShirt": [ {"size": "Small","quantity": 0}, {"size": "Medium","quantity": 5}, {"size": "Large","quantity": 3} ], "myShirt2": [ {"size": "Small","quantity": 2}, {"size": "Medium","quantity": 0}, {"size": "Large","quantity": 7} ] }; // Convert the object into an array of [productName, sizeData] pairs for easy mapping const productList = Object.entries(clothingData); return ( <div style={{ padding: '1rem' }}> {productList.map(([productName, sizes]) => { // Format each size-quantity pair into the required string const stockDetails = sizes.map(sizeEntry => `${sizeEntry.size}库存${sizeEntry.quantity}` ).join(' '); // Render each product line return ( <div key={productName} style={{ margin: '0.5rem 0' }}> <strong>{productName}</strong> {stockDetails} </div> ); })} </div> ); }; export default ClothingInventory;
Step 2: What This Does
Let's walk through the key parts:
Object.entries(clothingData): This takes your original JSON object and turns it into an array like[["myShirt", [...sizeData]], ["myShirt2", [...sizeData]]], which makes it easy to loop through each product withmap().- Formatting Stock Details: For each product, we loop through its size array, turn each entry into a string like
Small库存0, then join all those strings with spaces to match your desired format. - Key Prop: We use the product name as the
keyfor each rendered item (just make sure all your product names are unique—if not, you might need a different unique identifier).
Optional: Handle Zero Stock More Clearly
If you want to highlight out-of-stock items instead of showing 0, you can tweak the formatting line:
const stockDetails = sizes.map(sizeEntry => `${sizeEntry.size}库存${sizeEntry.quantity === 0 ? '*无库存*' : sizeEntry.quantity}` ).join(' ');
This will display *无库存* instead of 0 for sizes that are sold out, using asterisks to emphasize the text.
Output Preview
When you render this component, you'll get output like:
myShirt Small库存0 Medium库存5 Large库存3
myShirt2 Small库存2 Medium库存0 Large库存7
Or with the zero-stock tweak:
myShirt Small无库存 Medium库存5 Large库存3
myShirt2 Small库存2 Medium无库存 Large库存7
内容的提问来源于stack exchange,提问作者user2030942

