Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and remove object from json array

I am trying to search a object and remove from json array

my json array of object looks like

var data = [{
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
}];

What I am try to achieve is if I have a object with Id=1
I can search the array match it with array and remove it from the array.

I am trying this by below code

function RemoveNode(id)
{
 data.forEach(function (emp) {
   if(emp.Id == id)
    {
      delete emp;
    }
  }
}

I am not able to get it work, kindly suggest a better way to do this

like image 680
ankur Avatar asked Dec 18 '22 18:12

ankur


1 Answers

You're using not valid data structure, your array needs to be in square brackets []

For your case better to use filter function:

var data = [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
];

function RemoveNode(id) {
    return data.filter(function(emp) {
        if (emp.id == id) {
            return false;
        }
        return true;
    });
}

var newData = RemoveNode("1");

document.write(JSON.stringify(newData, 0, 4));
like image 150
isvforall Avatar answered Jan 02 '23 12:01

isvforall