Angular中遍历对象问题:原数组遍历代码适配对象输入
processPostData Got it, let's fix this issue! The problem here is that your data.resources used to be an array (or array-like), but now it's a plain object with keys like 23, 24, etc. The original Array.prototype.forEach.call approach won't work on plain objects because they don't have the array-like length property that method expects.
Here are two straightforward solutions depending on whether you need to keep the object keys or just process the values:
Option 1: Convert Object Values to an Array (Keep Existing Logic)
If you don't need the keys (like 23, 24) and just want to process each resource value exactly like you did with the array, use Object.values() to extract all values into an array. This will let you reuse almost all of your original code:
processPostData(data: any) { // Replace Array.prototype.forEach.call with Object.values().forEach Object.values(data.resources).forEach((element: any) => { console.log(element); Object.keys(element).forEach((key) => { console.log(key); if ((element[key] == null || element[key] == '') && ['process_limit_date', 'creation_date', 'closing_date', 'countAttachments', 'countNotes'].indexOf(key) === -1) { element[key] = this.lang.undefined; } else if (["senders","recipients"].indexOf(key) > -1) { // Fixed a typo here: was >0, should be >-1 to match both keys if (element[key].length > 1) { console.log(element[key]); element[key] = this.lang.isMulticontact; } else { element[key] = element[key][0]; } } else if (key == 'status_icon' && element[key] == null) { element[key] = 'fa-question undefined'; } }); }); return data; }
Option 2: Traverse Key-Value Pairs (If You Need the Object Keys)
If you need to access the keys (like 23, 24) during processing (for logging, conditional logic, etc.), use Object.entries() to get both the key and its corresponding value in each iteration:
processPostData(data: any) { Object.entries(data.resources).forEach(([resourceKey, element]: [string, any]) => { console.log(`Processing resource with key: ${resourceKey}`, element); Object.keys(element).forEach((key) => { console.log(key); if ((element[key] == null || element[key] == '') && ['process_limit_date', 'creation_date', 'closing_date', 'countAttachments', 'countNotes'].indexOf(key) === -1) { element[key] = this.lang.undefined; } else if (["senders","recipients"].indexOf(key) > -1) { if (element[key].length > 1) { console.log(element[key]); element[key] = this.lang.isMulticontact; } else { element[key] = element[key][0]; } } else if (key == 'status_icon' && element[key] == null) { element[key] = 'fa-question undefined'; } }); }); return data; }
Both approaches will work seamlessly with your new resources object structure. Option 1 is the most drop-in replacement since it maintains your original processing flow, while Option 2 gives you access to those numeric keys if you need them for additional logic.
内容的提问来源于stack exchange,提问作者Nathan Cheval

