Remove Specific JSON Object from JSON Array

Sovary August 5, 2022 417
1 minute read

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...

Javascript  Node.js 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him