0

I have an array of objects in JS

myArray = [
 {name: 'Jim', id: "2"}
 {name: 'Pam', id: "10"}
 {name: 'Dwight', id: "7"}
];

Given I have

var currentID = 2;

And I want to get the name from that array of objects where the id = 2 (all objects will have a unique ID field so there is no issue with multiple objects with the same ID) is there a better way than just doing this

testFunction() {
    var myArray = [
      { name: "Jim", id: "2" },
      { name: "Pam", id: "10" },
      { name: "Dwight", id: "7" },
    ];
    var currentID = "10";
    var currentName = "";

    for (let i in myArray) {
      console.log(i);
      if (myArray[i].id == currentID) {
        currentName = myArray[i].name;
        console.log(currentName);
        break;
      }
    }
  }

This will output "Pam" but i wanted to know if there is a more elegant way to index into that object without the need of a for loop? If not its not too much of an issue as I'm mostly just looking to clean up my code. Thanks!

0 Answers0