Find an object by id in a JavaScript object array


Joined
Aug 4, 2021
Messages
7
Reaction score
1
I have an array.
JavaScript:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
I can't change the structure of the array. I was passed an id 45 and I want to get the id of that object in the array 'bar'.

How can I do this in JavaScript or jQuery?
 
Ad

Advertisements

Joined
Nov 13, 2020
Messages
73
Reaction score
14
You did not include any of the code you tried to use to eliminate the element of the array, so I don't know how to show you your error.

Array elements are found by using square brackets: myArray[0]; myArray[1];
myArray is an array of object and could be called a JSON array.

I would use that knowledge to find the id of 45 and then delete that element from the array :
Code:
<p id="demo">Here</p>

<script>
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},{'id':'65','foo':'bar'},{'id':'55','foo':'bar'}];

var index = myArray.findIndex(x => x.id === '45');

if (index !== -1) myArray.splice(1, 1);
document.getElementById("demo").innerHTML = JSON.stringify(myArray);  //JUST TO SHOW THAT IT WAS REMOVED
</script>
</body>
 
Joined
Nov 13, 2020
Messages
73
Reaction score
14
Almost forgot. Putting your id numbers in quotes makes them a string. That's why I had to look for a string in the findIndex() function.
 
Ad

Advertisements

Joined
Aug 4, 2021
Messages
7
Reaction score
1
You did not include any of the code you tried to use to eliminate the element of the array, so I don't know how to show you your error.

Array elements are found by using square brackets: myArray[0]; myArray[1];
myArray is an array of object and could be called a JSON array.

I would use that knowledge to find the id of 45 and then delete that element from the array :
Code:
<p id="demo">Here</p>

<script>
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},{'id':'65','foo':'bar'},{'id':'55','foo':'bar'}];

var index = myArray.findIndex(x => x.id === '45');

if (index !== -1) myArray.splice(1, 1);
document.getElementById("demo").innerHTML = JSON.stringify(myArray);  //JUST TO SHOW THAT IT WAS REMOVED
</script>
</body>
Thank you so much! You solved my problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top