使用 JavaScript 从数组中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10024866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:32:52  来源:igfitidea点击:

Remove Object from Array using JavaScript

javascriptarrays

提问by Clem

How can I remove an object from an array? I wish to remove the object that includes name Kristianfrom someArray. For example:

如何从数组中删除对象?我希望KristiansomeArray. 例如:

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

回答by KooiInc

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, a.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.splicecombined with Array.findIndex(see MDN), e.g.

回复@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>

回答by psyho

I recommend using lodash.js or sugar.jsfor 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.

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

回答by Jon

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 workon IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.

问题在于它在 IE < 9 上不起作用。但是,您可以包含来自 Javascript 库(例如underscore.js)的代码,该库为任何浏览器实现了这一点。

回答by Allan Taylor

How about this?

这个怎么样?

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

回答by nnnnnn

Your "array" as shown is invalid JavaScript syntax. Curly brackets {}are for objects with property name/value pairs, but square brackets []are for arrays - like so:

如图所示,您的“数组”是无效的 JavaScript 语法。大括号{}用于具有属性名称/值对的对象,但方括号[]用于数组 - 如下所示:

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

In that case, you can use the .splice()methodto remove an item. To remove the first item (index 0), say:

在这种情况下,您可以使用.splice()方法删除项目。要删除第一项(索引 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);

回答by Saeid

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!

它将删除约翰

回答by daCoda

You could use array.filter().

您可以使用 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"}];

Arrow functions:

箭头函数:

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

回答by Bishoy Hanna

I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:

我制作了一个动态函数,它采用对象数组、键和值,并在删除所需对象后返回相同的数组:

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

        }

Full Example: 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"));

回答by ggmendez

This is a function that works for me:

这是一个对我有用的功能:

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

回答by Andre Morata

someArray = jQuery.grep(someArray , function (value) {
        return value.name != 'Kristian';
});