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
Multiple Row Grouping Datatables jQuery
Multiple Row Grouping Datatabl...

In this article, we will see how to row group in datatable in jquery. Datatables doesn't have row grouping buil...

Read More

Jun-04-2022

Laravel 11 Socialite Login with Gitlab Account
Laravel 11 Socialite Login wit...

Hello, Laravel web developers! In this article, I'll show you how to log in with GitLab in Laravel 11 using Socialit...

Read More

Aug-14-2024

Laravel 10 CRUD Operation Step By Step
Laravel 10 CRUD Operation Step...

In this article, we will see how to create a crud operation in laravel 10. Here, we will learn about laravel 10 crud ope...

Read More

Feb-24-2023

How To Get Current URL In React JS
How To Get Current URL In Reac...

As a React JS developer, I have come to appreciate the power and popularity of this remarkable JavaScript library. Its c...

Read More

Aug-09-2023