如何从数组中删除对象?我希望从中删除包含名称的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"}];
您可以使用多种方法从数组中删除项目:
//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, someArray.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));
回复@chill182Array.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(`let noJohn = someArray.filter( el => el.name !== "John")`,
`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("",
`someArray2 = someArray2.filter( el => el.name !== "John" )`,
`destructive filter/reassign John removed [someArray2] =`,
format(someArray2));
log(`**someArray2.length after filter ${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("",
`someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1),`,
`destructive splice /w findIndex Brian remains [someArray3] =`,
format(someArray3));
log(`**someArray3.length after splice ${someArray3.length}`);
// 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("", `someArray4.splice(indx, indx >= 0 ? 1 : 0)`,
`check findIndex result first [someArray4] = (nothing is removed)`,
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);
// -- helpers --
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>
干净的解决方案是使用Array.filter
:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
问题在于它不适用于 IE < 9。但是,您可以包含来自 Javascript 库(例如underscore.js)的代码,该库为任何浏览器实现此功能。
我建议使用 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"; });
在大多数项目中,拥有一组由此类库提供的辅助方法非常有用。
这个怎么样?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
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');
它将删除约翰!
如图所示,您的“数组”是无效的 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);
你可以使用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')
我制作了一个动态函数,获取对象数组、键和值,并在删除所需对象后返回相同的数组:
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;
}
你也可以尝试做这样的事情:
var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
在数组上使用拼接函数。指定开始元素的位置和要删除的子序列的长度。
someArray.splice(pos, 1);
为使用数组的简单工作投票支持UndercoreJS。
_.without()函数有助于删除元素:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
我们得到名称属性值为“Kristian”的对象的索引
const index = someArray.findIndex(key => key.name === "Kristian");
console.log(index); // 0
通过使用 splice 函数,我们正在删除 name 属性值为“Kristian”的对象
someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]
今天 2021.01.27,我在 Chrome v88、Safari v13.1.2 和 Firefox v84 上对 MacOs HighSierra 10.13.6 进行测试,以选择解决方案。
对于所有浏览器:
我执行 4 个测试用例:
下面的片段展示了解决方案 A B C D E F G H I之间的差异
function A(arr, name) {
let idx = arr.findIndex(o => o.name==name);
if(idx>=0) arr.splice(idx, 1);
return arr;
}
function B(arr, name) {
let idx = arr.findIndex(o => o.name==name);
return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}
function C(arr, name) {
let idx = arr.findIndex(o => o.name==name);
delete arr[idx];
return arr;
}
function D(arr, name) {
return arr.filter(el => el.name != name);
}
function E(arr, name) {
let result = [];
arr.forEach(o => o.name==name || result.push(o));
return result;
}
function F(arr, name) {
return _.reject(arr, el => el.name == name);
}
function G(arr, name) {
let o = arr.find(o => o.name==name);
return _.without(arr,o);
}
function H(arr, name) {
$.each(arr, function(i){
if(arr[i].name === 'Kristian') {
arr.splice(i,1);
return false;
}
});
return arr;
}
function I(arr, name) {
return $.grep(arr,o => o.name!=name);
}
// Test
let test1 = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
];
let test2 = [
{name:"John3", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
let test3 = [
{name:"John3", lines:"1,19,26,96"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);
[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
这是 chrome 的示例结果
这是一个带有 map 和 splice 的示例
const arrayObject = [
{ name: "name1", value: "value1" },
{ name: "name2", value: "value2" },
{ name: "name3", value: "value3" },
];
let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
arrayObject.splice(index, 1);
console.log("Result", arrayObject);
}
输出
Result [
{
"name": "name2",
"value": "value2"
},
{
"name": "name3",
"value": "value3"
}
]
带 ES 6 箭头功能
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}
];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)
虽然这可能不适合这种情况,但前几天我发现delete
如果您不需要更改数组的大小,您也可以使用关键字从数组中删除项目,例如
var myArray = [1,2,3];
delete myArray[1];
console.log(myArray[1]); //undefined
console.log(myArray.length); //3 - doesn't actually shrink the array down
最简单的解决方案是创建一个按名称存储每个对象的索引的映射,如下所示:
//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 );
如果要删除给定对象的所有出现(基于某些条件),请在 for 循环中使用 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 的对象。
您也可以使用地图功能。
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);
这个答案
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
}
不适用于满足条件的多个记录。如果您有两条这样的连续记录,则仅删除第一条,跳过另一条。你必须使用:
for (var i = someArray.length - 1; i>= 0; i--)
...
反而 。
你的数组语法似乎有一个错误,所以假设你的意思是一个数组而不是一个对象,Array.splice是你的朋友:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)
使用 javascript 的 splice() 函数。
你也可以使用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)
})
我想答案是非常分支和打结的。
您可以使用以下路径删除与现代 JavaScript 术语中给出的对象匹配的数组对象。
coordinates = [
{ lat: 36.779098444109145, lng: 34.57202827508546 },
{ lat: 36.778754712956506, lng: 34.56898128564454 },
{ lat: 36.777414146732426, lng: 34.57179224069215 }
];
coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };
removeCoordinate(coordinate: Coordinate): Coordinate {
const found = this.coordinates.find((coordinate) => coordinate == coordinate);
if (found) {
this.coordinates.splice(found, 1);
}
return coordinate;
}
这就是我使用的。
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
splice(i, 1) 其中 i 是数组的增量索引将删除对象。但请记住 splice 也会重置数组长度,因此请注意“未定义”。使用您的示例,如果您删除“Kristian”,那么在循环内的下一次执行中,i 将为 2,但 someArray 的长度为 1,因此如果您尝试删除“John”,您将收到“未定义”错误. 一个解决方案虽然不优雅,但有一个单独的计数器来跟踪要删除的元素的索引。
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>
这个概念使用剑道网格
var grid = $("#addNewAllergies").data("kendoGrid");
var selectedItem = SelectedCheckBoxList;
for (var i = 0; i < selectedItem.length; i++) {
if(selectedItem[i].boolKendoValue==true)
{
selectedItem.length= 0;
}
}
如果您知道数组中的对象没有任何属性(或者可能是唯一的),但是您有对要删除的对象的引用,则可以执行unregisterObject
以下方法中的操作:
let registeredObjects = [];
function registerObject(someObject) { registeredObjects.push(someObject); }
function unregisterObject(someObject) { registeredObjects = registeredObjects.filter(obj => obj !== someObject); }
let myObject1 = {hidden: "someValue1"}; // Let's pretend we don't know the hidden attribute
let myObject2 = {hidden: "someValue2"};
registerObject(myObject1);
registerObject(myObject2);
console.log(`There are ${registeredObjects.length} objects registered. They are: ${JSON.stringify(registeredObjects)}`);
unregisterObject(myObject1);
console.log(`There are ${registeredObjects.length} objects registered. They are: ${JSON.stringify(registeredObjects)}`);