javascript - 如何在箭头函数内的Angular中使用输入发送的对象属性(比第一级更深)?
问题描述
我正在使用 angular 7 并尝试在子组件中做一些事情:使用可以在对象的第一级或更深的输入属性。
我的子组件有这段代码:
if (this.values.filter(obj => obj[this.matchPropertyName] === $event[i].id).length === 0) {
...
}
this.matchPropertyName 是我的输入(可以是 'id'、'myProperty.id'、...)
对于单个级别(obj.id),此代码有效。但是,有时我需要从更深层次使用(obj.myProperty.id),但它不起作用。我怎样才能做到这一点?
如果还不够清楚,请告诉我。
我正在使用角度 7 和打字稿 3.2.4
解决方案
我认为没有内置解决方案,但您可以使用简单的split
and reduce
. 例如:
const value = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
将给出obj.myProperty.id
何时的值this.matchPropertyName="myProperty.id"
因此,在您的情况下,您可以像这样使用它:
const theValue = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
if (this.values.filter(obj => theValue === $event[i].id).length === 0) {
...
}
OP的最终结果:
myEventListener($event) {
if (this.values.filter(obj => this.resolveProperty(obj) === $event[i].id).length === 0) {
...
}
}
resolveProperty(obj) {
return this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
}
推荐阅读
- c# - 动态从 Xamarin Forms Picker 生成 FontSize
- microsoft-teams - 加载示例应用程序 microsoft-teams-sample-meetings-token 时清单解析失败
- ios - 如何在没有致命错误的情况下覆盖按钮选择
- reactjs - 调用 document.onpaste 后更新 React 状态?
- android - 在移动应用程序中安全调用 API 函数的适当 Google 服务是什么?
- javascript - Webservice 代理在一段时间后失去身份验证
- javascript - 如何通过 io-ts (typescript) 验证 Date 对象?
- python - 如何修复 plt.subplots 以使图更靠近?
- django - Django 使用 Big Integer 作为主键添加多对多
- r - 过滤和管道