从Javascript对象中删除单个对象
如何从以下javascript对象中删除基于courseID和endDate的一项从Javascript对象中删除单个对象,javascript,Javascript,如何从以下javascript对象中删除基于courseID和endDate的一项 window.MyCheckedCourses = [ { courseID: '123', endDate: '6/7/2010' }, { courseID: '123', endDate: '3/9/2003' }, { courseID: '456', endDate: '3/9/2003' } ]; 可以使用splice:MyChe
window.MyCheckedCourses = [
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
可以使用splice:
MyCheckedCourses.splice(索引,长度)从数组中删除元素代码>
例如:
MyCheckedCourses=[0,1,2,3];
MyCheckedCourses.splice(1,1);
MyCheckedCourses
现在是:[0,1,3]
要根据键值查找索引,可以使用:
// only returns the first found index
function findBy(arr,keys){
var i = 0,match,len;
for(i=0,len=arr.length;i<len;i++){
match=true;
for(key in keys){
if(arr[i][key]!==keys[key]){
match=false;
break
}
}
if(match===true){
return i;
}
}
return false;
}
var courses=[
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
var index = findBy(courses,
{courseID:"123",
endDate:"3/9/2003"}
);
if(index!==false){
courses.splice(index,1);
}
console.log(courses);
//只返回找到的第一个索引
功能查找方式(arr、键){
变量i=0,匹配,len;
for(i=0,len=arr.length;i迭代是必须的。您必须使用.splice()
删除相应的项并中断
for循环
var i, id = '123', date = '6/7/2010';
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
这不是一个对象,它是一个对象的“数组”。window.MyCheckedCourses
是一个数组,而不是jQuery对象。正如其他人所说,这是一个对象数组,与jQuery无关。您只需使用MyCheckedCourses.splice(startIndex,count);
从数组中删除您想要的元素。非常感谢大家的帮助。如何根据要删除的对象的courseID和endDate值从JavaScript对象数组中删除单个对象?@AllanHorwitz在数组上循环。按照您指定的方式访问该项的属性,并检查是否没有它们匹配所需的值。然后使用.splice()
。但是要小心,如果存在多个匹配,则需要从数组长度循环到0。虽然id
让我想到了“唯一”(我知道标题上写着“单个对象”,但这可能意味着在多个地方有一个“单个对象”),如果可能存在多个匹配项,则必须(删除中断;
并)循环返回。如果您是对的,伊恩,我将更新我的答案。
function remove(id, date) {
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
}
// Example usage:
remove('123', '6/7/2010');
function remove(id, date) {
for(var i = MyCheckedCourses.length - 1;i >= 0;i--) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
}
}
}
// Example usage:
remove('123', '6/7/2010');