admin管理员组文章数量:1221288
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'}
];
Now I want to delete {id:3,date:'2011-02-13',des:'badday'}
, and then the arr should be
var arr = [
{id:2,date:'2010-10-03',des:'goodday'},
{id:4,date:'2011-04-03',des:'niceday'}
];
How should I do?
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'}
];
Now I want to delete {id:3,date:'2011-02-13',des:'badday'}
, and then the arr should be
var arr = [
{id:2,date:'2010-10-03',des:'goodday'},
{id:4,date:'2011-04-03',des:'niceday'}
];
How should I do?
Share Improve this question asked Apr 12, 2011 at 2:59 CynialCynial 6808 silver badges23 bronze badges3 Answers
Reset to default 15Assume the id fields in you Objects are unique you can do the following to delete it. The function to use is 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'}
// ];
See here:
http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array
arr.splice(1,1);
will remove the object at arr[1]
,
and arr[2]
will slide into its place.
本文标签: javascriptHow to delete an item from array of objectsStack Overflow
版权声明:本文标题:javascript - How to delete an item from array of objects? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739337207a2158762.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论