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'}
];
我应该怎么做?
最佳答案
假设您对象中的 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'}
// ];
关于javascript - 如何从对象数组中删除项目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5629914/