如何遍历嵌套字典labels并调用drawLabels?修复遍历代码问题
The issue here is that your labels variable is an object (dictionary), not an array. Arrays have a length property and support index-based access like labels[i], but objects don’t—they rely on key-value pairs instead. Here are a few straightforward ways to fix your code:
Solution 1: Convert Object Values to an Array (Simplest)
Use Object.values() to extract all the label objects into an array, then loop through that array just like you originally tried:
// Convert the object's values into an array const labelArray = Object.values(labels); for (let i = 0; i < labelArray.length; i++) { const label = labelArray[i]; drawLabels(label.id, label.xMin, label.xMax, label.yMin, label.yMax); }
Or even shorter with a forEach loop (cleaner for simple iterations):
Object.values(labels).forEach(label => { drawLabels(label.id, label.xMin, label.xMax, label.yMin, label.yMax); });
Solution 2: Iterate Over Object Keys
If you need to keep track of the original keys (like "1", "2", etc.), use Object.keys() to get the list of keys, then access each label by its key:
const labelKeys = Object.keys(labels); for (let i = 0; i < labelKeys.length; i++) { const key = labelKeys[i]; const label = labels[key]; drawLabels(label.id, label.xMin, label.xMax, label.yMin, label.yMax); }
Solution 3: Use a for...in Loop
You can also loop directly over the object’s properties with a for...in loop. Just add a hasOwnProperty check to avoid iterating over inherited properties (a best practice for object loops):
for (const key in labels) { if (labels.hasOwnProperty(key)) { const label = labels[key]; drawLabels(label.id, label.xMin, label.xMax, label.yMin, label.yMax); } }
Bonus: If You Can Modify the Original Structure
If you control how labels is created, consider storing it as an array of objects from the start. That way your original loop would work perfectly:
// Rewrite labels as an array instead of an object const labels = [ {"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"}, {"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"}, {"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"}, {"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"} ]; // Your original loop now works! for (let i = 0; i < labels.length; i++){ drawLabels( labels[i].id, labels[i].xMin, labels[i].xMax, labels[i].yMin, labels[i].yMax ); }
All these methods will let you iterate through each label and call drawLabels correctly. Pick the one that fits your use case best!
内容的提问来源于stack exchange,提问作者lara

