如何从数组中删除对象?
我希望从Kristian
中删除包含名称someArray
的对象。例如:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
我想实现:
someArray = [{name:"John", lines:"1,19,26,96"}];
答案 0 :(得分:681)
您可以使用多种方法从数组中删除项目:
//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
如果要删除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}`);
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>
答案 1 :(得分:127)
我建议您使用underscore.js或sugar.js执行以下常见任务:
// underscore.js
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });
// sugar.js
someArray.remove(function(el) { return el.Name === "Kristian"; });
在大多数项目中,拥有一组由这些库提供的辅助方法非常有用。
答案 2 :(得分:92)
这个怎么样?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
答案 3 :(得分:85)
干净的解决方案是使用Array.filter
:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
这个问题是IE上的does not work&lt; 9.但是,您可以包含来自Javascript库的代码(例如underscore.js),以便为任何浏览器实现此功能。
答案 4 :(得分:65)
如图所示,您的“数组”是无效的JavaScript语法。卷括号{}
用于具有属性名称/值对的对象,但方括号[]
用于数组 - 如下所示:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
在这种情况下,您可以使用.splice()
method删除项目。要删除第一个项目(索引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()
method:
someArray = $.grep(someArray,
function(o,i) { return o.name === "Kristian"; },
true);
答案 5 :(得分:49)
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');
它将删除 John !
答案 6 :(得分:22)
您可以使用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')
答案 7 :(得分:18)
我已经创建了一个动态函数获取对象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"));
答案 8 :(得分:14)
这是一个适合我的功能:
function removeFromArray(array, value) {
var idx = array.indexOf(value);
if (idx !== -1) {
array.splice(idx, 1);
}
return array;
}
答案 9 :(得分:11)
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
答案 10 :(得分:8)
投票使用UndercoreJS进行数组的简单工作。
_.without()函数有助于删除元素:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
答案 11 :(得分:8)
在数组上使用splice函数。指定起始元素的位置以及要删除的子序列的长度。
someArray.splice(pos, 1);
答案 12 :(得分:7)
今天 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 的示例结果
答案 13 :(得分:7)
您也可以尝试这样做:
public class MainViewModel : INotifyPropertyChanged
{
private SerialPort sp = new SerialPort();
public ObservableCollection<SerialPort> PortsList{ get; set; }
private SerialPort _selectedPort;
public SerialPort SelectedPort
{
get { return _selectedPort; }
set
{
_selectedPort = value;
NotifyPropertyChanged("SelectedPort");
}
}
public MainViewModel()
{
DefaultValue_Load();
}
public void DefaultValue_Load()
{
//what should I do
PortsList = new ObservableCollectioin<SerialPort>();
}
}
答案 14 :(得分:4)
使用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)
答案 15 :(得分:3)
虽然这可能不适合这种情况,但前几天我发现如果你不需要改变数组的大小,你也可以使用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
答案 16 :(得分:3)
此答案
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--)
...
相反。
答案 17 :(得分:2)
您的数组语法似乎有错误,所以假设您的意思是数组而不是对象,Array.splice是您的朋友:
someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)
答案 18 :(得分:2)
您也可以使用地图功能。
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);
答案 19 :(得分:2)
我猜答案是非常分支和打结的。
您可以使用以下路径删除与现代JavaScript术语中给出的对象匹配的数组对象。
flex-direction: column;
答案 20 :(得分:2)
最简单的解决方案是创建一个按名称存储每个对象索引的映射,如下所示:
//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 );
答案 21 :(得分:2)
如果要删除所有出现的给定对象(基于某些条件),请在循环中使用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的所有对象。
答案 22 :(得分:2)
这就是我使用的。
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
答案 23 :(得分:1)
仅返回属性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>
答案 24 :(得分:1)
这里是地图和拼接的例子
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);
}
答案 25 :(得分:1)
splice(i,1)其中i是数组的增量索引将删除对象。 但请记住,splice也会重置数组长度,因此请注意“未定义”。使用你的例子,如果你删除&#39; Kristian&#39;,那么在循环中的下一次执行中,我将是2但someArray将是1的长度,因此如果你试图删除&#34; John&# 34;你会得到一个未定义的&#34;错误。对此的一个解决方案虽然不优雅,但是具有单独的计数器以跟踪要移除的元素的索引。
答案 26 :(得分:1)
使用javascript splice()函数。
答案 27 :(得分:0)
使用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;
}
}
答案 28 :(得分:0)
您也可以使用some
:
org.bouncycastle.x509.extension.X509ExtensionUtil
答案 29 :(得分:0)
如果您知道数组中的对象没有任何属性(或者可能是唯一的),但您有对要删除的对象的引用,则可以执行 {{ 1}} 方法如下:
unregisterObject
答案 30 :(得分:0)
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
通过使用 splice 函数,我们删除了名称属性值为“Kristian”的对象
someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]
答案 31 :(得分:-2)
如果你想访问和删除数组的对象,你可以尝试这样的事情。
// 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 }];