gpt4 book ai didi

javascript - Angular 1/Javascript - lodash 省略和删除运算符的替代方案

转载 作者:行者123 更新时间:2023-12-03 03:36:51 25 4
gpt4 key购买 nike

我有一个子组件,我必须在其中删除对象的属性。

通常使用 Lodash 应该可以使用以下代码:

this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent'])

只是current.obj模型没有挂载到父组件

但是如果我仅使用运算符delete从对象中删除属性,它就可以工作

   delete this.current.obj.sellerSupportAgency
delete this.current.obj.sellerSupportWeb
delete this.current.obj.sellerSupportAgent

是否没有其他替代方法可以完成与删除和省略相同的工作?

我不知道它是否有帮助,但为了让它与 omit 一起工作,我在子组件上调用父对象(父组件),以便我可以使用它,但我正在寻找另一个解决方案,因为current.obj

for (const [index] of this.current.parent.items.entries()) {
this.current.parent.items[index] = omit(this.current.parent.items[index], ['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent'])
}

最佳答案

如果我理解正确的话,您想要修改组件与其父组件之间共享的对象。该对象位于父组件的数组中,因此我假设您正在使用 ng-repeat 语句。我不确定,因为您没有共享组件定义,也没有在父组件模板中共享实例化。

当您更改本地对象引用(使用omit)时,父组件中的数组将不会被修改。当您就地更改本地对象(使用删除)时,本地变量仍将引用父数组中的对象,并且它将在两个地方进行修改(因为它是同一个对象)。

长话短说,您必须选择修改数组(在父级中),还是从本地对象中删除字段(删除是唯一的方法)。前者会更像 Angular ,特别是如果您使用“&”类型事件处理程序告诉父组件您希望从对象中删除某些字段。然后你可以做这样的事情:

angular.component(...
bindings: {
filterObjectHandler: '&onFilterObject'
(...)

this.filterObjectHandler(['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent']);

或者类似的东西。有一组有趣的文章here关于 AngularJS 1.5+ 中的组件结构。

但是,如果您只是想要一种以涉及带有字段数组的单行的方式删除字段的方法,您可以使用以下方法:

var obj = this.current.obj;

['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent'].forEach(function(field) {
delete obj[field];
});

甚至:

['sellerSupportWeb', 'sellerSupportAgency', 'sellerSupportAgent'].reduce(function(obj, field) {
delete obj[field];
return obj;
}, this.current.obj);

关于javascript - Angular 1/Javascript - lodash 省略和删除运算符的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com