如何删除列表对象中list_items里not_visible为false的子项?
Hey there! Let's work through this problem together. I see you're trying to remove entries in list_items where not_visible is false, but ran into issues with nested forEach loops. Let's break down the fixes and better approaches.
首先修复你的forEach写法
Your original code was almost there—you just missed the actual deletion step, plus a small typo in the return statement. Here's the corrected version:
getListsObjectByNameItemVisibility: function() { var lists = listsObjectByName(this); Object.entries(lists).forEach( ([key, value]) => { Object.entries(value['list_items']).forEach( ([subKey, subValue]) => { if(subValue['not_visible'] === false){ // 删除符合条件的list_items条目 delete value['list_items'][subKey]; } }); }); // 注意这里返回的是lists,不是list(原代码的变量名错误) return lists; }
为什么这样能行?
When you loop through value (each list object in lists), you're working with a reference to the original object. So using delete value['list_items'][subKey] directly modifies the original list_items object—no issues with accessing parent values here. The main missing piece was the delete statement, plus fixing the return variable name from list to lists.
更优雅的函数式写法(推荐)
If you prefer avoiding direct mutations of the original object (which is often better for code predictability), you can use Object.fromEntries combined with filter and map to create a new filtered object:
getListsObjectByNameItemVisibility: function() { const lists = listsObjectByName(this); // 遍历外层lists,处理每个列表的list_items const filteredLists = Object.fromEntries( Object.entries(lists).map(([key, listObj]) => { // 过滤list_items,只保留not_visible不为false的条目 const filteredItems = Object.fromEntries( Object.entries(listObj.list_items).filter(([itemKey, item]) => { return item.not_visible !== false; }) ); // 返回新的列表对象,替换原有的list_items return [key, {...listObj, list_items: filteredItems}]; }) ); return filteredLists; }
这个写法的优势:
- It doesn't modify the original
listsobject, so you avoid unintended side effects. - The code is more declarative—you can clearly see we're creating filtered versions of the data instead of modifying it in place.
- It's easier to debug and test since it's pure (no external state changes).
最后检查点
Make sure listsObjectByName(this) returns an object where each value has a list_items property that's also an object (not an array)—your code assumes this structure, so if list_items is an array instead, we'd need to adjust to use filter() directly on the array.
内容的提问来源于stack exchange,提问作者morne

