[英]Delete an object from a nested array of objects
我有這個小函數(在Angular 7
應用程序中),它使用JavaScript reduce()
,並在嵌套的對象數組中定位對象。 然后,我可以繼續動態更新某些屬性。
現在,除了這種查找邏輯外,我還想將對象插入/從嵌套數組中insert/delete
。
問題是:一旦找到對象,是否可以push()和/或刪除對象?
const input={UID:2,GUID:"",LocationName:"USA",ParentLocation:null,subs:[{UID:42,GUID:"",LocationName:"New Jersey",Description:"",subs:[{UID:3,GUID:"",LocationName:"Essex County",ParentLocation:null,"subs":[{UID:4,LocationName:"Newark",ParentLocation:3,"subs":[{"UID":49,"GUID":"","LocationName":"Doctor Smith's Office","LocationType":{"UID":2,"LocationTypeName":"Practice","Description":"other location"},"subs":[{"HostID":38,"HostName":"Ocean Host",}]}]}]}]}]}; const findUIDObj = (uid, parent) => { const { UID, subs } = parent; if (UID === uid) { const { subs, ...rest } = parent; return rest; } if (subs) return subs.reduce((found, child) => found || findUIDObj(uid, child), null); }; console.log(findUIDObj(49, input)); var obj = findUIDObj(49, input); delete obj;
例如,在我的Angular 7應用程序中,它抱怨我是否嘗試delete
找到的對象:
EX /
var obj = findUIDObj(49, input);
delete obj;
'delete' cannot be called on an identifier in strict mode.
簡要查看您的代碼,我發現您正在使用const
標識符來聲明數據收集。 我們僅將const
用於不變的靜態數據,這就是它的目的。 因此,首先,這似乎是問題所在。 要對其進行測試,請將其更改為let
。 現在,關於數據管理方法,出於許多原因,不可變性值得您考慮,但是Angular會重新渲染整個對象,而不管更改現有對象或接收新對象。 您可以查找不可變JavaScript以了解更多信息。 在許多情況下,創建不可變數據管理是通過庫完成的,您可以自己完成。 基本上,創建一個名為copy( data )
的函數或類似的函數,以便您傳入原始對象,但是在沒有引用原始對象的情況下,您將獲得該函數的副本。 這樣一來,就不會意外更改原始對象。 為此,您可以在復制函數內部執行以下操作: return JSON.parse(JSON.stringify( data )) ;
您可能在這里遇到的唯一問題是深層嵌套的對象,否則帶有循環引用的對象可能會引起問題。 我有一個最重要的stringify
方法可以在我編寫的小庫中進行管理。
delete obj
永遠不會做您想要的事情:首先,它甚至不是您輸入中的對象,因為該函數從找到的對象中創建了一個新對象(不包括subs
屬性),並返回了該對象。 但更重要的是, delete
用於刪除屬性,而不是對象。
似乎您想從其父subs
屬性中刪除匹配的對象。 為此,您需要對subs
數組進行突變,因此它將排除匹配的對象。 為了使它以通用方式工作,您的輸入應為數組。 否則,該根對象無法從任何內容中刪除。
考慮到這一點,您的查找函數應該返回在其中找到匹配項以及在哪個索引處的數組。 利用這些信息,您可以決定從數組中刪除該元素,或在該索引處插入另一個對象。
這是刪除時的工作方式:
const input=[{UID:2,GUID:"",LocationName:"USA",ParentLocation:null,subs:[{UID:42,GUID:"",LocationName:"New Jersey",Description:"",subs:[{UID:3,GUID:"",LocationName:"Essex County",ParentLocation:null,"subs":[{UID:4,LocationName:"Newark",ParentLocation:3,"subs":[{"UID":49,"GUID":"","LocationName":"Doctor Smith's Office","LocationType":{"UID":2,"LocationTypeName":"Practice","Description":"other location"},"subs":[{"HostID":38,"HostName":"Ocean Host",}]}]}]}]}]}]; const findUIDObj = (uid, arr) => { if (!arr) return; const idx = arr.findIndex(obj => obj.UID === uid); if (idx > -1) return [arr, idx]; for (const obj of arr) { const result = findUIDObj(uid, obj.subs); if (result) return result; } }; console.log(findUIDObj(49, input)); const [arr, idx] = findUIDObj(49, input) || []; if (arr) { arr.splice(idx, 1); // Remove object from its parent array }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.