简体   繁体   English

使用 JavaScript 从数组中删除 Object

[英]Remove Object from Array using JavaScript

How can I remove an object from an array?如何从数组中删除 object? I wish to remove the object that includes name Kristian from someArray .我希望从 someArray 中删除包含名称KristiansomeArray For example:例如:

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

I want to achieve:我想实现:

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

You can use several methods to remove item(s) from an Array:您可以使用多种方法从数组中删除项目:

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

If you want to remove element at position x , use:如果要删除 position x处的元素,请使用:

someArray.splice(x, 1);

Or要么

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

Reply to the comment of @chill182 : you can remove one or more elements from an array using Array.filter , or Array.splice combined with Array.findIndex (see MDN ).回复@chill182的评论:你可以使用Array.filterArray.splice结合Array.findIndex从数组中删除一个或多个元素(参见MDN )。

See this Stackblitz project or the snippet below:请参阅此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>

The clean solution would be to use Array.filter :干净的解决方案是使用Array.filter

var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; }); 

The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (eg underscore.js ) that implements this for any browser.问题是它在 IE < 9 上不起作用。但是,您可以包含 Javascript 库(例如underscore.js )中的代码,为任何浏览器实现此功能。

I recommend using lodash.js or sugar.js for common tasks like this:我建议使用 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"; });

in most projects, having a set of helper methods that is provided by libraries like these is quite useful.在大多数项目中,拥有一组由此类库提供的辅助方法非常有用。

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

It will remove John !它将删除John

How about this?这个怎么样?

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

Your "array" as shown is invalid JavaScript syntax.显示的“数组”无效 JavaScript 语法。 Curly brackets {} are for objects with property name/value pairs, but square brackets [] are for arrays - like so:大括号{}用于具有属性名称/值对的对象,而方括号[]用于 arrays - 如下所示:

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

In that case, you can use the .splice() method to remove an item.在这种情况下,您可以使用.splice()方法删除一个项目。 To remove the first item (index 0), say:要删除第一项(索引 0),请说:

someArray.splice(0,1);

// someArray = [{name:"John", lines:"1,19,26,96"}];

If you don't know the index but want to search through the array to find the item with name "Kristian" to remove you could to this:如果您不知道索引但想搜索数组以找到名称为“Kristian”的项目以将其删除,您可以这样做:

for (var i =0; i < someArray.length; i++)
   if (someArray[i].name === "Kristian") {
      someArray.splice(i,1);
      break;
   }

EDIT: I just noticed your question is tagged with "jQuery", so you could try the $.grep() method :编辑:我刚刚注意到你的问题被标记为“jQuery”,所以你可以尝试$.grep()方法

someArray = $.grep(someArray,
                   function(o,i) { return o.name === "Kristian"; },
                   true);

You could use array.filter().你可以使用 array.filter()。

eg例如

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

Arrow functions:箭头函数:

someArray = someArray.filter(x => x.name !== 'Kristian')

I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:我做了一个动态的 function 获取对象数组、键和值,并在删除所需的 object 后返回相同的数组:

function removeFunction (myObjects,prop,valu)
        {
             return myObjects.filter(function (val) {
              return val[prop] !== valu;
          });

        }

Full Example: DEMO完整示例: 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"));

This is a function that works for me:这是对我有用的 function:

function removeFromArray(array, value) {
    var idx = array.indexOf(value);
    if (idx !== -1) {
        array.splice(idx, 1);
    }
    return array;
}
const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];

We get the index of the object which have name property value as "Kristian"我们得到 object 的索引,其名称属性值为“Kristian”

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

By using splice function we are removing the object which have the name property value as "Kristian"通过使用拼接 function,我们将删除 object,其名称属性值为“Kristian”

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

You could also try doing something like this:你也可以尝试做这样的事情:

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

Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.在arrays上使用function拼接。指定起始元素的position和要删除的子序列的长度。

someArray.splice(pos, 1);

Vote for the UndercoreJS for simple work with arrays.投票给 UndercoreJS 以使用arrays进行简单的工作。

_.without() function helps to remove an element: _.without() function 有助于删除一个元素:

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

Here is an example with map and splice这是 map 和拼接的示例

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

Output Output

Result [
  {
    "name": "name2",
    "value": "value2"
  },
  {
    "name": "name3",
    "value": "value3"
  }
]

Performance表现

Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.今天 2021.01.27 我在 Chrome v88、Safari v13.1.2 和 Firefox v84 上针对所选解决方案对 MacOs HighSierra 10.13.6 进行了测试。

Results结果

For all browsers:对于所有浏览器:

  • fast/fastest solutions when element not exists: A and B元素不存在时的快速/最快解决方案:A 和 B
  • fast/fastest solutions for big arrays: C大 arrays 的快速/最快解决方案:C
  • fast/fastest solutions for big arrays when element exists: H元素存在时大 arrays 的快速/最快解决方案:H
  • quite slow solutions for small arrays: F and G小 arrays 的相当慢的解决方案:F 和 G
  • quite slow solutions for big arrays: D, E and F大 arrays 的相当慢的解决方案:D、E 和 F

在此处输入图像描述

Details细节

I perform 4 tests cases:我执行 4 个测试用例:

  • small array (10 elements) and element exists - you can run it HERE小数组(10 个元素)和元素存在 - 你可以在这里运行它
  • small array (10 elements) and element NOT exists - you can run it HERE小数组(10 个元素)和元素不存在 - 你可以在这里运行它
  • big array (milion elements) and element exists - you can run it HERE大数组(milion 元素)和元素存在 - 你可以在这里运行它
  • big array (milion elements) and element NOT exists - you can run it HERE大数组(milion 元素)和元素不存在 - 你可以在这里运行它

Below snippet presents differences between solutions A B C D E F G H I下面的片段展示了解决方案之间的差异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,GHI].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!

And here are example results for chrome这是 chrome 的示例结果

在此处输入图像描述

With ES 6 arrow function带 ES 6 箭头 function

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)

Although this is probably not that appropriate for this situation I found out the other day that you can also use the delete keyword to remove an item from an array if you don't need to alter the size of the array eg虽然这可能不太适合这种情况,但前几天我发现如果不需要更改数组的大小,也可以使用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

Simplest solution would be to create a map that stores the indexes for each object by name, like this:最简单的解决方案是创建一个 map 按名称存储每个 object 的索引,如下所示:

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

You can use map function also.您也可以使用map function。

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

If you want to remove all occurrences of a given object (based on some condition) then use the javascript splice method inside a for the loop.如果要删除给定 object 的所有出现(基于某些条件),请在 for 循环内使用 javascript 拼接方法。

Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.由于删除 object 会影响数组长度,因此请确保将计数器递减一步,以便长度检查保持不变。

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

The above code snippet removes all objects with age greater than 20.上面的代码片段删除了所有年龄大于 20 的对象。

This answer这个答案

for (var i =0; i < someArray.length; i++)
   if (someArray[i].name === "Kristian") {
      someArray.splice(i,1);
   }

is not working for multiple records fulfilling the condition.不适用于满足条件的多个记录。 If you have two such consecutive records, only the first one is removed, and the other one skipped.如果你有两个这样的连续记录,只有第一个被删除,另一个被跳过。 You have to use:你必须使用:

for (var i = someArray.length - 1; i>= 0; i--)
   ...

instead.反而。

I guess the answers are very branched and knotted.我想答案非常分支和打结。

You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.您可以使用以下路径删除与现代 JavaScript 行话中给出的 object 匹配的数组 object。


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

There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:您的数组语法中似乎有错误,因此假设您指的是数组而不是 object, Array.splice是您的朋友:

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

Use javascript's splice() function.使用 javascript 的 splice() function。

This may help: http://www.w3schools.com/jsref/jsref_splice.asp这可能有帮助: http://www.w3schools.com/jsref/jsref_splice.asp

You could also use some :你也可以使用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) 
})

This is what I use.这是我用的。

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

Then it is as simple as saying那么说起来就简单了

var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);

Replace any number in place of three.用任意数字代替三。 After the expected output should be:预期的output之后应该是:

console.log(myArray); //Expected output 1,2,3,5,6,7,8,9

splice(i, 1) where i is the incremental index of the array will remove the object. But remember splice will also reset the array length so watch out for 'undefined'. splice(i, 1) 其中 i 是数组的增量索引,将删除 object。但请记住,splice 也会重置数组长度,因此请注意“未定义”。 Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error.使用您的示例,如果您删除“Kristian”,那么在循环中的下一次执行中,i 将为 2 但 someArray 的长度将为 1,因此如果您尝试删除“John”,您将收到“未定义”错误. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.一个解决方案虽然不优雅,但有一个单独的计数器来跟踪要删除的元素的索引。

Returns only objects from the array whose property name is not "Kristian"仅返回属性name不是“Kristian”的数组中的对象

var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });


Demo: 演示:

 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>

This Concepts using 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;
    }
}

If you don't have any properties on the objects in the array that you know (or perhaps that are unique), but you have a reference to the object that you want to remove, you can do what's in the unregisterObject method below:如果您知道数组中的对象没有任何属性(或者可能是唯一的),但您有对要删除的对象的引用,则可以执行以下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)}`);

_collection = this._collection.filter(x => x.key != key);

How can I remove an object from an array?如何从数组中删除对象? I wish to remove the object that includes name Kristian from someArray .我希望从someArray删除包含名称Kristian的对象。 For example:例如:

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

I want to achieve:我要实现:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM