【问题标题】:Delete Object From An Array Of Object [duplicate]从对象数组中删除对象[重复]
【发布时间】:2015-01-22 02:03:14
【问题描述】:

我有一个这样的对象数组

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)

【问题讨论】:

  • 试试Array.prototype.filter

标签: javascript arrays node.js socket.io


【解决方案1】:

就像 Taylor 在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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      猜你喜欢
      • 2018-08-28
      • 1970-01-01
      • 2020-04-15
      • 2016-03-12
      • 2021-07-01
      • 2014-08-24
      • 1970-01-01
      相关资源
      最近更新 更多