我有这个小功能(在我的Angular 7
应用程序内),它使用JavaScript reduce()
,并在嵌套的对象数组中定位一个对象。然后,我可以继续动态更新某些属性。
现在,除了这种查找逻辑之外,我还想将对象抄入嵌套数组/从嵌套数组中抄出。
问题是:一旦找到对象,是否可以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应用中,如果我尝试
insert/delete
找到的对象,它会抱怨:前/
var obj = findUIDObj(49, input);
delete obj;
'delete' cannot be called on an identifier in strict mode.
最佳答案
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
}