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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With