【问题标题】:How to use in Angular inside an arrow function an object property (deeper than 1st level) sent by input?如何在箭头函数内的Angular中使用输入发送的对象属性(比第一级更深)?
【发布时间】:2021-10-14 04:34:37
【问题描述】:

我正在使用 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),但它不起作用。 我怎样才能做到这一点?

如果还不够清楚,请告诉我。

我正在使用 angular 7 和 typescript 3.2.4

【问题讨论】:

  • 一个“好的”解决方案是规范化您的数据并确保 id 始终在顶级可用..

标签: javascript angular typescript arrow-functions angular-input


【解决方案1】:

我认为没有内置解决方案,但您可以使用简单的splitreduce。例如:

const value = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);

this.matchPropertyName="myProperty.id" 时会给出obj.myProperty.id 的值

Stackblitz

所以在你的情况下,你可以像这样使用它:

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);   
}

【讨论】:

  • 非常感谢您的大力帮助!我略微调整了您的建议,因为“obj”在“theValue”表达式中是未知的,因为它来自箭头函数 this.values.filter。 => 所以我做了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); }
  • @pti_jul 啊,是的,我猜我在变量命名中迷路了 :-) 很高兴你明白了
  • 确实,后来我认为变量命名在我阅读您的 stackblitz 时造成了混淆(感谢您的时间!)。再次感谢,你帮我完成了我的 JIRA 票,是最后剩下的事情 :)
  • 哈哈很好,很高兴能帮上忙! :-)
猜你喜欢
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 2021-06-28
  • 2019-01-27
  • 2017-12-13
  • 2018-06-28
  • 1970-01-01
相关资源
最近更新 更多