How To Remove Specific JSON Object From Array Javascript

In this article, we will see how to remove a specific JSON object from an array javascript. we need to add a JavaScript function that takes in one such array as the first argument and the id string in the second argument for search and removing objects from the JSON array.

So, let's see how to search object by id and remove it from a JSON array in javascript, jquery find an object by id in an array,  remove an element from a JSON object, remove an object from JSON array jquery, JSON array removes element by value.

Example : 

const arr = [
   {id: "1", name: "car", type: "vehicle"},
   {id: "2", name: "bike", type: "vehicle"},
   {id: "3", name: "cycle", type: "vehicle"},
   {id: "4", name: "red", type: "color"},
   {id: "5", name: "green", type: "color"},
   {id: "6", name: "blue", type: "color"},

];

const removeById = (arr, id) => {
   const requiredIndex = arr.findIndex(el => {
      return el.id === String(id);
   });
   if(requiredIndex === -1){
      return false;
   };
   return !!arr.splice(requiredIndex, 1);
};
removeById(arr, 5);
console.log(arr);

Output :

[
   {id: "1", name: "car", type: "vehicle"},
   {id: "2", name: "bike", type: "vehicle"},
   {id: "3", name: "cycle", type: "vehicle"},
   {id: "4", name: "red", type: "color"},
   {id: "6", name: "blue", type: "color"},

]

 


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS