如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:

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

我想实现:

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

当前回答

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

其他回答

我做了一个动态函数,以对象数组,键和值,并返回相同的数组后删除所需的对象:

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

我想答案是非常分支和复杂的。

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

虽然这可能不适合这种情况,我发现前几天,如果你不需要改变数组的大小,你也可以使用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

你可以这样过滤:

const someArray = [{ 名称:“克里斯蒂安”, 行:“2、5、10” }, { 名称:“约翰”, :“96”1,19日,26日 } ]; var filtered = someArray.filter((el) => el.name != "Kristian"); console.log(过滤)

这就是我用的。

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

用任何数字代替3。之后的预期输出应该是:

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