使用JavaScript从数组中删除对象

如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:

someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];

我想实现:

someArray = [{name:"John", lines:"1,19,26,96"}];
1428589 次浏览

在数组上使用拼接函数。指定开始元素的位置和要删除的子序列的长度。

someArray.splice(pos, 1);

您可以使用多种方法从数组中删除项目:

//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

如果要删除位置x的元素,请使用:

someArray.splice(x, 1);

someArray = someArray.slice(0, x).concat(someArray.slice(-x));

回复@陈志立的评论:您可以使用Array.filterArray.spliceArray.findIndex组合从数组中删除一个或多个元素(参见MDN)。

请参阅此stackblitz项目或下面的片段:

// 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)的代码,该库为任何浏览器实现了这一点。

最简单的解决方案是创建一个映射,按名称存储每个对象的索引,如下所示:

//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 );

您的“数组”如图所示是无效的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.splice是你的朋友:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)

我建议使用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"; });

在大多数项目中,拥有一组由这些库提供的辅助方法是非常有用的。

虽然这可能不适合这种情况,但我前几天发现,如果您不需要更改数组的大小,您也可以使用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

使用javascript的plice()函数。

这可能会有所帮助:http://www.w3schools.com/jsref/jsref_splice.asp

这个怎么样?

$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});

UndercoreJS投票,以便简单地处理数组。

_没有()函数有助于删除元素:

 _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

我做了一个动态函数,接受对象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"));
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});

这是一个对我有用的函数:

function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}

plice(i,1)其中i是数组的增量索引将删除对象。 但请记住,plice也会重置数组长度,因此要注意“未定义”。使用您的示例,如果您删除“Kristian”,那么在循环中的下一次执行中,i将为2,但某些数组的长度将为1,因此如果您尝试删除“John”,您将获得“未定义”错误。一个解决方案虽然不优雅,但有一个单独的计数器来跟踪要删除的元素的索引。

您可以使用array.filter()。

e. g.

        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')

仅返回属性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>

您也可以使用地图函数。

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)
})

你也可以尝试这样做:

var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);

使用剑道网格的概念

var grid = $("#addNewAllergies").data("kendoGrid");


var selectedItem = SelectedCheckBoxList;


for (var i = 0; i < selectedItem.length; i++) {
if(selectedItem[i].boolKendoValue==true)
{
selectedItem.length= 0;
}
}

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');

它将删除约翰

具有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)

这就是我使用的。

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

如果您想删除给定对象的所有出现(基于某些条件),请在for循环中使用javascript拼接方法。

由于删除对象会影响数组长度,因此请确保将计数器递减一步,以便长度检查保持不变。

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的对象。

这个答案

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--)
...

相反。

我想答案是非常分叉和打结的。

您可以使用以下路径删除与现代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;
}

这是一个使用map和plice的示例

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"
}
]

性能

今天2021.01.27我在Chromev88、Safariv13.1.2和Firefox v84上对MacO HighSierra 10.13.6进行测试,以获取所选解决方案。

搜索结果

对于所有浏览器:

  • 元素不存在时的快速/最快解决方案:A和B
  • 大数组的快速/最快解决方案:C
  • 元素存在时大数组的快速/最快解决方案:H
  • 小数组的相当慢的解决方案:F和G
  • 大数组的相当慢的解决方案:D、E和F

在此处输入图片描述

详情

我执行4个测试用例:

  • 小数组(10个元素)和元素存在-您可以运行它这里
  • 小数组(10个元素)和元素不存在-您可以运行它这里
  • 大数组(百万元素)和元素存在-您可以运行它这里
  • 大数组(百万元素)和元素不存在-你可以运行它这里

下面的代码片段显示了解决方案之间的差异 A B C D E F G H

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的示例结果

在此处输入图片描述

如果你在数组中的对象上没有任何你知道的属性(或者可能是唯一的),但是你有一个要删除的对象的引用,你可以执行下面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)}`);

const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];

我们得到具有name属性值为“Kristian”的对象的索引

const index = someArray.findIndex(key => key.name === "Kristian");
console.log(index); // 0

通过使用拼接函数,我们删除了名称属性值为“Kristian”的对象

someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]

你可以像这样过滤:

const someArray = [{
name: "Kristian",
lines: "2,5,10"
},
{
name: "John",
lines: "1,19,26,96"
}
];
var filtered = someArray.filter((el) => el.name != "Kristian");
console.log(filtered)