I am getting a response of an api that includes an array that has many objects inside of it . The objects positions change overtime. Therefore if I use array[0] the object it returns might change depending on the current arrangement of the objects. How can I access a specific object in the array regardless of the index so that even if the indexes positions change the same object is accessed?
4 Answers
You're gonna need some way to identify the object you're looking for. For example, if the object has a specific property with a specific value, you can use that to find this object in the array. To actually find the object, you can use Array.prototype.find.
For example, if you're always looking for the object with an id of 123:
const testArray = [{ id: 123 }, { id: 456 }, { id: 789 }];
const idToSearchFor = 123;
const objectWithSpecificId = testArray.find(
obj => obj.id === idToSearchFor
);
If you want to find multiple objects instead of one, you can use Array.prototype.filter:
const testArray = [{ id: 123 }, { id: 456 }, { id: 789 }];
const idsFilter = [123, 789];
const matchingObjects = testArray.filter(
obj => idsFilter.includes(obj.id)
);
console.log(matchingObjects.length); // 2
2 Comments
akvn
Thank you! Is there a way by any chance in which I can find more than one element without having to repeat the code? ( A way in which I put all the IDs I want and I get all the objects which contain all the IDs I put where I can use a loop to extract what I want from all of them at once) ?
MoritzLost
@AkonZ In this case you can use Array.prototype.filter instead, I've updated my answer with an example!
idin the object to identify it? Find object by id in an array of JavaScript objects