首页 > 解决方案 > 如何在箭头函数内的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

标签: javascriptangulartypescriptarrow-functionsangular-input

解决方案


我认为没有内置解决方案,但您可以使用简单的splitand 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);   
}

推荐阅读