-1

I Have an Array of objects like this

var persons = [
  {p_id:1000, name:"jhon", age:25, sex:"male"},
  {p_id:1001, name:"lisa", age:30, sex:"female"},
  {p_id:1002, name:"robert", age:29, sex:"male"}
]

I want to delete person where the key is p_id = 1001 (lisa) so my array become :

var persons = [
  {p_id:1000, name:"jhon", age:25, sex:"male"},
  {p_id:1002, name:"robert", age:29, sex:"male"}
]

note : - Not using jquery because this is server side javascript (node.js)

Firdaus
  • 43
  • 6

3 Answers3

0

Try Array.prototype.splice:

var persons = [
  {p_id:1000, name:"jhon", age:25, sex:"male"},
  {p_id:1001, name:"lisa", age:30, sex:"female"},
  {p_id:1002, name:"robert", age:29, sex:"male"}
]
persons.splice(0,1);
console.log(persons); //-> array without the first element

Here's some documentation: MDN

rioc0719
  • 284
  • 2
  • 11
0

To remove the item with p_id=1001 you can use filter():

persons = persons.filter(function(item) { return item.p_id !== 1001; });
Andreas Argelius
  • 3,464
  • 1
  • 11
  • 22
  • 1
    This does not remove the item from the existing array. This creates a new array with the item excluded. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Taylor Buchanan Jan 22 '15 at 02:26
0

Like Taylor pointed out from this post, you can get the index and use splice() to remove it. Here is the code:

var persons = [
  {p_id:1000, name:"jhon", age:25, sex:"male"},
  {p_id:1001, name:"lisa", age:30, sex:"female"},
  {p_id:1002, name:"robert", age:29, sex:"male"}
];

var index = -1;
for (var i = 0, len = persons.length; i < len; i++) {
  if (persons[i].p_id === 1001) {
    index = i;
    break;
  }
}

if (index > -1) {
  persons.splice(index, 1);
}

console.log(persons);  // output and array contains 1st and 3rd items
Community
  • 1
  • 1
Ben
  • 4,757
  • 2
  • 15
  • 22