Search and remove object from json array

10,453

Solution 1

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));

Solution 2

A better way might be to filter your original array to remove the item you dont want.

Assuming data is really an array of objects (ie, does not have the error currently in your question)

function RemoveNode(id){
    return data.filter(function(e){
        return e.id !== id;
    });
}

You could also use splice, however that would require knowing the index of the item you want to remove, and by the time you've found that you may as well just filter!

Solution 3

Consider this following code with forEach & splice, assuming data is array of objects:

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){
    data.forEach(function(e, index){
    if(id == e.id){
        data.splice(index, 1);
    }
  })
}
RemoveNode(1);
console.log(data);
Share:
10,453
ankur
Author by

ankur

Updated on June 19, 2022

Comments

  • ankur
    ankur almost 2 years

    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