3

I'm using angular 7 and trying to do something in a child component : use the input property that can be at first level in the object or deeper.

My child component has this piece of code :

if (this.values.filter(obj => obj[this.matchPropertyName] === $event[i].id).length === 0) {
  ...
}

where this.matchPropertyName is my input (can be 'id', 'myProperty.id',...)

For a single level (obj.id) this code works. However, I need to use sometimes from a deeper level (obj.myProperty.id) and it doesn't work. How can I achieve this ?

Let me know if it not clear enough.

I'm using angular 7 and typescript 3.2.4

eko
  • 39,722
  • 10
  • 72
  • 98
pti_jul
  • 432
  • 1
  • 5
  • 18
  • a 'good' solution would be to normalize your data and make sure the id is always available at top level I'm afraid.. – MikeOne Aug 10 '21 at 17:12

1 Answers1

3

I don't think there's a built-in solution but you can make use of a simple split and reduce. For example:

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

would give the value for obj.myProperty.id when this.matchPropertyName="myProperty.id"

Stackblitz

So in your case, you could use it like:

const theValue = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
if (this.values.filter(obj => theValue === $event[i].id).length === 0) {
  ...
}

Final result by the 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);   
}
pti_jul
  • 432
  • 1
  • 5
  • 18
eko
  • 39,722
  • 10
  • 72
  • 98
  • Many thanks for your great help ! I've slighlty adapt your suggestion as 'obj ' is unknown in "theValue" expression as it comes from the arrow function this.values.filter. => So I did `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 Aug 11 '21 at 06:36
  • @pti_jul ah yes I got lost in the variable naming I guess :-) Glad you figured it out though – eko Aug 11 '21 at 07:57
  • 1
    Indeed, I thought afterwards that the variable naming made confusion where I read your stackblitz (thanks for your time !). Thanks again, you helped me finish my JIRA ticket, was the last remaining thing :) – pti_jul Aug 11 '21 at 08:16
  • Haha nice, glad I could help! :-) – eko Aug 11 '21 at 08:18