从对象数组中删除对象

时间:2015-01-22 02:03:14

标签: javascript arrays node.js socket.io

我有一个像这样的对象

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"}
]

我想删除密钥是p_id = 1001(lisa)的人,所以我的数组变为:

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

注意: - 不使用jquery,因为这是服务器端javascript(node.js)

3 个答案:

答案 0 :(得分:0)

尝试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

以下是一些文档:MDN

答案 1 :(得分:0)

要删除带有p_id = 1001的项目,您可以使用filter()

persons = persons.filter(function(item) { return item.p_id !== 1001; });

答案 2 :(得分:0)

就像泰勒从this post指出的那样,你可以得到索引并使用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"}
];

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