0

I have an array of objects: [obj1, obj2, obj3]

obj1 = {id:1,name:First}
obj2 = {id:2,name:Second}
...

But the object's array indexes are constantly changing. How else can I reference a specific object given only its id property? The goal is to set a variable equal to the name property (e.g. obj1's name = First). In other words, how can I reference an object's property given the key to a different property?

Any help would be greatly appreciated! Thank you!

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
Joe Lee
  • 31
  • 6
  • Can you give us more details about the programming language you are using? – François Noël Mar 22 '18 at 18:29
  • Using Mocha, Chai, supertest, and JavaScript to test API endpoints. Trying to write a unit-test for a delete endpoint. But to do that, I need to get an object's *name* using only its *id* number from the response body containing the array of objects. – Joe Lee Mar 22 '18 at 18:33
  • I'm not sure I understood your question, but have you tried to use a Map data structure? – Leonardo Alves Machado Mar 23 '18 at 19:58

1 Answers1

0

There is multiple ways to achieve this, it only depends on performance requirement. Here's a Stack Overflow thread that I think solve your question:

Find a value in an array of objects in Javascript

I am also adding my favorite solution here:

ES6 Array.prototype.find function

var id = 1;
var arr = [{...},...];
var obj = arr.find(o => o.id === id);
François Noël
  • 426
  • 4
  • 13