将多值嵌套对象转换为特定格式数组的技术实现问询
Got it, let's work through this problem together. Your data object has a nested generalInfo array where each item contains a nested category array—so I’m assuming you want to flatten or restructure this into a cleaner, more usable array (since you mentioned "specific format," I’ll cover common practical use cases below).
Basic Implementation: Flatten to Single-Level Objects
This is the most common scenario: extract key details from the nested category array and create a flat object for each product. We’ll handle edge cases like empty category arrays and fix the typo (curreny → currency) in your original data to avoid bugs.
const data = { "generalInfo": [ { "title": "title1", "permalink": "www.link.com", "manufacturer": "manufacturer1", "category": [{ "term_id": 35, "name": "Motherboard", "slug": "motherboard" }], "img": "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg", "currency": "$", // Fixed typo from "curreny" "price": "64.00", "availability": "Usually ships in 24 hours" }, { "title": "title2", "permalink": "www.link.com", "manufacturer": "manufacturer2", "category": [] // Example of empty category } ] }; // Transform to flat array of product objects const transformedArray = data.generalInfo.map(product => { // Handle empty/missing category arrays with default values const primaryCategory = product.category?.[0] || { name: "Uncategorized", slug: "uncategorized" }; return { productTitle: product.title, productUrl: product.permalink, brand: product.manufacturer, category: primaryCategory.name, categorySlug: primaryCategory.slug, imageUrl: product.img, formattedPrice: `${product.currency || "$"}${product.price || "0.00"}`, stockStatus: product.availability || "Out of stock" }; }); console.log(transformedArray);
Alternative: Handle Multiple Categories
If your products can belong to multiple categories, here are two flexible options:
Option A: Combine Categories into a Single String
Great for displaying categories in UI:
const withCombinedCategories = data.generalInfo.map(product => { const categoryNames = product.category?.map(cat => cat.name).join(", ") || "Uncategorized"; return { ...product, // Keep all original fields categoryNames: categoryNames, // Add combined category string // Optional: Remove the original nested category array to clean up ...Object.fromEntries(Object.entries(product).filter(([key]) => key !== "category")) }; });
Option B: Expand into Multiple Entries (One per Category)
Use flatMap if you need a separate array entry for each product-category pair (useful for filtering or analytics):
const expandedEntries = data.generalInfo.flatMap(product => { // Fallback to a single "Uncategorized" entry if no categories exist const categories = product.category.length ? product.category : [{ name: "Uncategorized" }]; return categories.map(category => ({ title: product.title, brand: product.manufacturer, category: category.name, price: `${product.currency}${product.price}` // Add other fields as needed })); });
Key Notes
- Error Prevention: Used optional chaining (
?.) and default values to avoid crashes if fields likecategoryorpriceare missing. - Typo Fix: Your original data had
currenyinstead ofcurrency—I corrected this in examples to ensure currency formatting works as expected. - Customization: Adjust the returned object in
map/flatMapto match your exact "specific format" requirements (add/remove fields, rename keys, reorder properties, etc.).
内容的提问来源于stack exchange,提问作者Carol.Kar

