使用JavaScript从数组中删除对象

2020/09/23 23:41 · javascript ·  · 0评论

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

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

我要实现:

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

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

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

如果要删除position处的元素x,请使用:

someArray.splice(x, 1);

要么

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

回复@ chill182的评论:您可以使用Array.filterArray.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>

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

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

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

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

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

这个怎么样?

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

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

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

它将删除约翰

您可以使用array.filter()。

例如

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

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

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

function removeFromArray(array, value) {
    var idx = array.indexOf(value);
    if (idx !== -1) {
        array.splice(idx, 1);
    }
    return array;
}
someArray = jQuery.grep(someArray , function (value) {
        return value.name != 'Kristian';
});

您也可以尝试执行以下操作:

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

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

someArray.splice(pos, 1);

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

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

 _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    => [2, 3, 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)

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

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

虽然这可能不适合这种情况,但有一天我发现,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 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的对象。

这个答案

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

相反。

数组语法中似乎有一个错误,因此假设您的意思是数组而不是对象,Array.splice是您的朋友:

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

使用javascript的splice()函数。

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

您也可以使用地图功能。

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

这就是我用的。

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

我猜答案是非常分支和打结的。

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

splice(i,1)其中i是数组的增量索引将删除对象。但是请记住,拼接也会重置数组长度,因此请注意“ undefined”。以您的示例为例,如果删除“ Kristian”,则在循环内的下一次执行中,我将为2,但someArray的长度为1,因此,如果尝试删除“ John”,则会收到“未定义”错误。尽管不是很优雅的一种解决方案是具有单独的计数器以跟踪要删除的元素的索引。

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

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

如果您想访问和删除数组的对象,只需尝试以下操作即可。

// 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 }];
        
本文地址:http://javascript.askforanswer.com/shiyongjavascriptcongshuzuzhongshanchuduixiang.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!