0

Angular: I have a variable, myNumber = 5 and an array of objects, ids and names. nameArray: Nameset[] = [];

The array looks like this:

0: {id: 1, name: "Jim"}
1: {id: 3, name: "Bob"}
2: {id: 5, name: "Carl"}

What is the best way to the the matching name from the array where id === myNumber

I always use a forEach loop like this, but is this the best way?

getName(myNumber) {
    let helper = '';
    this.nameArray.forEach(aNameset => {
      if (aNameset.id === myNumber) {
        helper = aNameset.name;
      }
    })
    return helper;
  }
Jan Bürger
  • 111
  • 2
  • 9
  • 1
    There are 2 ways. 1 - change your array to this: nameArray = { 1: "Jim", 3: "Bob" 5: "Carl" } and just call `this.nameArray[myNumber]` 2 - replace getName with `return this.nameArray.find(el => el.id === myNumber).map(el => el.name);` – akim lyubchenko May 05 '20 at 14:09
  • I am using your second way. Works just fine. Thanks for your help. – Jan Bürger May 05 '20 at 16:06

0 Answers0