In this tutorial we will learn how to delete specific an JSON item from array. We will implement in pure JavaScript which you can use in front-end or back-end with Node.js as well. We will create a function which required two parameters, one is the JSON array to check and second is id or key which distinct unique each JSON item to remove that object.
So let's see below example to search JSON object by id and remove element which exist in array data, find an object by id in an array, remove an element from a JSON object, remove an object from array JSON , JSON array removes element by value.
Example:
const arr = [{
"id": 1,
"name": "Carey Speenden",
"gender": "Agender"
}, {
"id": 2,
"name": "Luisa Quarlis",
"gender": "Female"
}, {
"id": 3,
"name": "Damiano McVity",
"gender": "Male"
}, {
"id": 4,
"name": "Ruthi Skea",
"gender": "Female"
}, {
"id": 5,
"name": "Morganne Bruun",
"gender": "Female"
}];
const removeById = (arr, id) =>
{
const index = arr.findIndex(el =>
{
return el.id === id;
});
if(index === -1)
{
return false;
};
return !!arr.splice(index, 1);
};
removeById(arr, 3);
// After remove
console.log(arr);
Output:
[
{ id: 1, name: 'Carey Speenden', gender: 'Agender' },
{ id: 2, name: 'Luisa Quarlis', gender: 'Female' },
{ id: 4, name: 'Ruthi Skea', gender: 'Female' },
{ id: 5, name: 'Morganne Bruun', gender: 'Female' }
]
Hope this article help you. Have a nice day!
You might also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him