Find an object by id in a JavaScript object array

Joined
Aug 4, 2021
Messages
11
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?
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
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
302
Reaction score
38
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.
 
Joined
Aug 4, 2021
Messages
11
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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top