从对象数组中删除对象
Delete Object From An Array Of Object
我有一个这样的对象数组
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.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
要删除带有 p_id=1001 的项目,您可以使用 filter()
:
persons = persons.filter(function(item) { return item.p_id !== 1001; });
正如 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
我有一个这样的对象数组
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.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
要删除带有 p_id=1001 的项目,您可以使用 filter()
:
persons = persons.filter(function(item) { return item.p_id !== 1001; });
正如 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