【发布时间】:2019-04-30 20:02:41
【问题描述】:
我有这个小函数(在我的 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 找到的对象,它会报错:
前/
var obj = findUIDObj(49, input);
delete obj;
'delete' cannot be called on an identifier in strict mode.
【问题讨论】:
-
据我了解,您无法在严格模式下删除嵌套对象。您必须创建一个过滤掉指定对象的新对象。
-
delete也不适用于数组...它会留下孔并且不会改变长度。使用splice()从数组中删除对象,因此您需要确定数组中的索引 -
另外,如果要“删除”的对象是根对象,那应该怎么办?为了更加一致,您的
input对象应该是一个类似于subs数组的数组。 -
我不会使用
delete运算符。我会简单地返回对象的副本,而不包含您不需要的东西。 -
在严格模式下,您可以使用 delete 从对象中删除属性。
标签: javascript angular typescript multidimensional-array angular7