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
How To Show Loading Spinner In Ajax jQuery
How To Show Loading Spinner In...

In this article, we will see how to show loading spinner in ajax jquery. Using ajaxStart() and ajaxStop() method we...

Read More

Jul-06-2022

Laravel 8 Many To Many Polymorphic Relationship
Laravel 8 Many To Many Polymor...

In this tutorial we will see laravel 8 many to many polymorphic relationship. many to many polymorphic relationship more...

Read More

Nov-22-2021

How To Validate Upload File Type Using Javascript
How To Validate Upload File Ty...

This article will show us how to validate upload file type using javascript. Using this post we can easily check the sel...

Read More

Aug-03-2020

How to Create Apexcharts Pie Chart in Laravel 11
How to Create Apexcharts Pie C...

Hello developers! In this article, we'll see how to create apexcharts pie chart in laravel 11. ApexCharts...

Read More

Apr-19-2024