How to Search Object by ID and Remove It from JSON Array In JavaScript

Websolutionstuff | May-26-2021 | Categories : PHP jQuery

In this example we will see how to search object by id and remove it from json array in javascript. we need to add JavaScript function that takes in one such array as the first argument and id string in second argument for search and remove object from json array.

After that this function search for the object by that id, and if the array contains that object, we should remove object from json array in javascript.So, let's learn how to remove object from json array in javascript.

Example : 

const arr = [
   {id: "1", name: "car", type: "vehicle"},
   {id: "2", name: "bike", type: "vehicle"},
   {id: "3", name: "cycle", type: "vehicle"},
   {id: "4", name: "pink", type: "color"},
   {id: "5", name: "blue", type: "color"},
   {id: "6", name: "red", 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: "pink", type: "color"},
   {id: "6", name: "red", type: "color"},

]

 

Recommended Post
Featured Post
Special Characters Not Allowed Validation In Laravel 9
Special Characters Not Allowed...

In this article, we will see special characters not allowed validation in laravel 9. Here, we will learn special ch...

Read More

Dec-23-2022

How To Create Parallax Scrolling Effect Using jQuery
How To Create Parallax Scrolli...

In this article, we will see how to create a parallax scrolling effect using jquery. Parallax scrolling is a websit...

Read More

May-04-2022

How to Uninstall Composer on Ubuntu 23.04
How to Uninstall Composer on U...

Hey there! If you've found your way to this guide, chances are you're looking to bid farewell to Composer on you...

Read More

Jan-22-2024

Laravel 9 Where Condition Example
Laravel 9 Where Condition Exam...

In this article, we will see laravel 9 where condition example. Where condition is essential in each and every quer...

Read More

Oct-12-2022