如何获取嵌套对象中ID键层级下Item对象的name属性?
Hey there! I see exactly what's tripping you up—your order.items uses dynamic product IDs as its keys, which is why order.items.id returns undefined (there’s no actual property named id on that object). Let’s break down simple ways to grab those item.name values:
1. Get All Item Names at Once
If you want to loop through every item in the order and pull their names, use Object.values() to extract all the item entries from the items object, then iterate over them:
// Loop through each item entry and log the name Object.values(order.items).forEach(itemEntry => { console.log(itemEntry.item.name); });
This will print each item’s name one by one, like Chocoholick Delight, Elite Happiness, etc.
2. Access a Specific Item's Name by ID
If you know the exact product ID you want to target, use bracket notation (instead of dot notation) to access the entry, then drill down to the name property:
// Replace with your target item ID const targetItemId = '5eee66c4a27a66807cf2bea5'; console.log(order.items[targetItemId].item.name); // Output: "Chocoholick Delight"
Bracket notation works here because it lets you use dynamic strings (like those product IDs) as property keys—dot notation only works for fixed, valid variable names.
3. Collect All Names into an Array
If you want to gather all item names into a single array for later use, swap forEach() for map():
const allItemNames = Object.values(order.items).map(itemEntry => itemEntry.item.name); console.log(allItemNames); // Output: ["Chocoholick Delight", "Elite Happiness", ...]
The core takeaway: your items object uses dynamic, string-based keys (the product IDs), so fixed dot notation won’t work. Using Object.values() to access all entries, or bracket notation with specific IDs, will let you reach those item.name properties smoothly.
内容的提问来源于stack exchange,提问作者Ross

