如何从数组中删除对象?我想删除,其中包括名称的对象Kristian
从someArray
。例如:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
我要实现:
someArray = [{name:"John", lines:"1,19,26,96"}];
如何从数组中删除对象?我想删除,其中包括名称的对象Kristian
从someArray
。例如:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
我要实现:
someArray = [{name:"John", lines:"1,19,26,96"}];
Answers:
您可以使用多种方法从数组中删除项目:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, a.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
如果要删除position处的元素x
,请使用:
someArray.splice(x, 1);
要么
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
回复@ chill182的评论:您可以使用Array.filter
或Array.splice
结合使用Array.findIndex
(参见MDN)从数组中删除一个或多个元素,例如
// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" );
log("non destructive filter > noJohn = ", format(noJohn));
log(`**someArray.length ${someArray.length}`);
// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("", "destructive filter/reassign John removed > someArray2 =",
format(someArray2));
log(`**someArray2.length ${someArray2.length}`);
// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("", "destructive splice /w findIndex Brian remains > someArray3 =",
format(someArray3));
log(`**someArray3.length ${someArray3.length}`);
// Note: if you're not sure about the contents of your array,
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", "check findIndex result first > someArray4 (nothing is removed) > ",
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);
function format(obj) {
return JSON.stringify(obj, null, " ");
}
function log(...txt) {
document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}
function getArray() {
return [ {name: "Kristian", lines: "2,5,10"},
{name: "John", lines: "1,19,26,96"},
{name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**
</pre>
findIndex
在中使用它之前,您应该检查结果splice
。如果数组中没有匹配的元素,则条件findIndex
将返回-1
,直接将其放入splice
将导致数组中最后一个元素的任意删除。
我建议对此类常见任务使用lodash.js或sugar.js:
// lodash.js
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });
// sugar.js
someArray.remove(function(el) { return el.Name === "Kristian"; });
在大多数项目中,像这样的库提供一组辅助方法非常有用。
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });
someArray = someArray.filter(function(e) { return e.Name !== "Kristian"; });
干净的解决方案是使用Array.filter
:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
这样做的问题是它在IE <9上不起作用。但是,您可以包括来自Java库的代码(例如underscore.js),该代码可为任何浏览器实现此功能。
someArray = someArray.filter(function(el) { return el.Name != "Kristian"; });
这个问题,不是吗?
这个怎么样?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
$.each()
在循环之前会缓存数组长度,因此,如果删除一个元素,$.each()
它将超出(现在更短)数组的末尾。(因此someArray[i]
将会undefined
并且undefined.name
将会崩溃。)
所示的“数组”是无效的JavaScript语法。圆括号{}
用于具有属性名称/值对的对象,而方括号[]
用于数组-像这样:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
在这种情况下,您可以使用该.splice()
方法删除项目。要删除第一项(索引0),请说:
someArray.splice(0,1);
// someArray = [{name:"John", lines:"1,19,26,96"}];
如果您不知道索引,但想在数组中搜索以找到要删除的名称为“ Kristian”的项目,则可以这样做:
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
break;
}
编辑:我刚刚注意到您的问题被标记为“ jQuery”,所以您可以尝试该$.grep()
方法:
someArray = $.grep(someArray,
function(o,i) { return o.name === "Kristian"; },
true);
$.grep()
吗?在此示例中,它并没有增加太多,是的,我可以放进去!=
,但是在其他情况下,您可能已经定义了一个函数,该函数恰好对您要grep的内容进行了相反的测试,因此,而不是定义一个附加功能,您可以仅使用该重载来反转结果。
function isEven(num) { return num%2===0 }
。您可以用来$.grep(someArray, isEven)
从数组中仅获取偶数,或者$.grep(someArray, isEven, true)
进行相反的操作以获取非偶数。
ES2015
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
someArray = someArray.filter(person => person.name != 'John');
它将删除约翰!
您可以使用array.filter()。
例如
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray = someArray.filter(function(returnableObjects){
return returnableObjects.name !== 'Kristian';
});
//someArray will now be = [{name:"John", lines:"1,19,26,96"}];
箭头功能:
someArray = someArray.filter(x => x.name !== 'Kristian')
我制作了一个动态函数,将对象Array,Key和value删除,并在删除所需对象后返回相同的数组:
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
完整示例:DEMO
var obj = {
"results": [
{
"id": "460",
"name": "Widget 1",
"loc": "Shed"
}, {
"id": "461",
"name": "Widget 2",
"loc": "Kitchen"
}, {
"id": "462",
"name": "Widget 3",
"loc": "bath"
}
]
};
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
console.log(removeFunction(obj.results,"id","460"));
这是一个对我有用的函数:
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
最简单的解决方案是创建一个按名称存储每个对象的索引的映射,如下所示:
//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );
//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );
数组语法中似乎有一个错误,因此假设您的意思是数组而不是对象,Array.splice是您的朋友:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)
您也可以使用地图功能。
someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
if(obj.name !== "Kristian"){
newArray.push(obj);
}
});
someArray = newArray;
console.log(someArray);
您还可以使用some
:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray.some(item => {
if(item.name === "Kristian") // Case sensitive, will only remove first instance
someArray.splice(someArray.indexOf(item),1)
})
这就是我用的。
Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}
那就这么简单
var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);
用任何数字代替三。预期输出后应为:
console.log(myArray); //Expected output 1,2,3,5,6,7,8,9
如果要删除所有出现的给定对象(基于某种条件),请在循环中使用javascript splice方法。
由于删除对象会影响数组的长度,因此请确保将计数器递减一级,以使长度检查保持不变。
var objArr=[{Name:"Alex", Age:62},
{Name:"Robert", Age:18},
{Name:"Prince", Age:28},
{Name:"Cesar", Age:38},
{Name:"Sam", Age:42},
{Name:"David", Age:52}
];
for(var i = 0;i < objArr.length; i ++)
{
if(objArr[i].Age > 20)
{
objArr.splice(i, 1);
i--; //re-adjust the counter.
}
}
上面的代码段删除了所有年龄大于20的对象。
使用javascript的splice()函数。
这可能会有所帮助:http : //www.w3schools.com/jsref/jsref_splice.asp
仅返回属性name
不是“ Kristian” 的数组中的对象
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
var someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });
console.log(noKristianArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
使用Kendo Grid的本概念
var grid = $("#addNewAllergies").data("kendoGrid");
var selectedItem = SelectedCheckBoxList;
for (var i = 0; i < selectedItem.length; i++) {
if(selectedItem[i].boolKendoValue==true)
{
selectedItem.length= 0;
}
}
如果您想访问和删除数组的对象,只需尝试以下操作即可。
// inside some function
let someArray = [ {"ColumnName" : "a", "PropertySerno" : 100005,"UpdateType" : 1},
{"ColumnName" : "b", "PropertySerno" : 100202,"UpdateType" : 1,
"ShowRemoveButton" : true} ];
for (let item of someArray) {
delete item.ShowRemoveButton;
}
console.log(item.outputMappingData.Data);
//output will be like that = [ {"ColumnName" : "a", "PropertySerno" : 100005,"UpdateType" : 1},
// {"ColumnName" : "b", "PropertySerno" : 100202,"UpdateType" : 1 }];