如何从对象数组中删除一个项目?
2011-04-12
9896
var arr = [
{id:2,date:'2010-10-03',des:'goodday'},
{id:3,date:'2011-02-13',des:'badday'},
{id:4,date:'2011-04-03',des:'niceday'}
];
现在我想删除
{id:3,date:'2011-02-13',des:'badday'>
,那么arr应该是
var arr = [
{id:2,date:'2010-10-03',des:'goodday'},
{id:4,date:'2011-04-03',des:'niceday'}
];
我该怎么办?
3个回答
假设您的对象中的 id 字段是唯一的,您可以执行以下操作来删除它。要使用的函数是 Splice :
var arr = [
{
id: 2,
date: '2010-10-03',
des: 'goodday'},
{
id: 3,
date: '2011-02-13',
des: 'badday'},
{
id: 4,
date: '2011-04-03',
des: 'niceday'}
];
for(var i=0; i<arr.length; i++){
if(arr[i].id == 3){
arr.splice(i, 1); //removes 1 element at position i
break;
}
}
console.log(arr);
//should give you
// var arr = [
// {id:2,date:'2010-10-03',des:'goodday'},
// {id:4,date:'2011-04-03',des:'niceday'}
// ];
KJYe.Name
2011-04-12
cwharris
2011-04-12
arr.splice(1,1);
将移除
arr[1]
处的对象,而
arr[2]
将滑入其位置。
kennebec
2011-04-12