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?
Asked
Active
Viewed 3,115 times
0
-
do your object has something unique? like id or unique name – alcatraz Jul 13 '21 at 12:21
-
1What is the meaning of *"same object"*? If you are getting the response from an API, it will always be brand new objects in the array. Do you have any property like `id` in the object to identify it? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150) – adiga Jul 13 '21 at 12:21
4 Answers
2
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

MoritzLost
- 2,611
- 2
- 18
- 32
-
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) ? – akvn Jul 13 '21 at 13:14
-
@AkonZ In this case you can use Array.prototype.filter instead, I've updated my answer with an example! – MoritzLost Jul 13 '21 at 14:20
0
You'll need a unique property on the object. Then you can use the find
method. Something like const target = myArray.find(obj => obj.id === "thing-im-looking-for");
0
If each object has a unique identifier you can use simply use find
array method. It might look like this:
var result = objectsArr.find(obj => {
return obj.id === id
})

Kiril
- 131
- 5