使用JavaScript从数组中删除对象

JavaScript

ItachiJinJin

2020-03-12

如何从数组中删除对象?我想删除,其中包括名称的对象KristiansomeArray例如:

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

我要实现:

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

第1157篇《使用JavaScript从数组中删除对象》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

17个回答
斯丁米亚Green 2020.03.12

If you wanna access and remove object of an array simply you can try something like this.

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

神无Green前端 2020.03.12

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

Returns only objects from the array whose property name is not "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>

路易Near番长 2020.03.12

You could also use 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) 
})
LPro 2020.03.12

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.

Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.

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.

Sam神乐番长 2020.03.12

具有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)
老丝Eva 2020.03.12

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:

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

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:

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

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 .

猴子十三 2020.03.12

You can use map function also.

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);
Harry逆天 2020.03.12

UndercoreJS投票以简化数组的工作。

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

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

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

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

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

someArray.splice(pos, 1);
神奇Eva 2020.03.12

我制作了一个动态函数,将对象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"));
GreenTonyL 2020.03.12

所示的“数组”是无效的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;
   }

EDIT: I just noticed your question is tagged with "jQuery", so you could try the $.grep() method:

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

我建议对此类常见任务使用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"; });

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

别坑我路易 2020.03.12

干净的解决方案是使用Array.filter

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

这样做的问题是它不能在IE <9上运行。但是,您可以包括来自Java库的代码(例如underscore.js),该代码可为任何浏览器实现此功能。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android