使用名称/值从数组中移除元素

27

我有以下数组

var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];

我该如何通过名称或id从这个数组中删除一个项?

谢谢

11个回答

54

我为此创建了一个方便的函数。

function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      array.splice(index, 1);
    }    
  });
}

//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

10
注意:使用此函数需要jQuery。 - Headshota
7
这不会破坏索引吗?因为在执行过程中,如果删除了一个元素,索引就会改变。 - Alex
@JohnStrickler:你能不用jQuery重写一下吗?我不喜欢使用库。 - Mimouni
根据文档 http://api.jquery.com/each/ ,$.each 不再接受两个参数了吗? - KVM
谢谢。运行得很好 :-) - Karan

35
Array.prototype.removeValue = function(name, value){
   var array = $.map(this, function(v,i){
      return v[name] === value ? null : v;
   });
   this.length = 0; //clear original array
   this.push.apply(this, array); //push all elements except the one we want to delete
}

countries.results.removeValue('name', 'Albania');

3
+1:这不是最高评分的答案,但对我来说效果最好。我正在解析从 jQuery AJAX 成功处理程序返回的 JSON 数组,而 $ .each 方法意外地出现了“未定义”的值。我仍然不确定为什么一开始会返回“未定义”的值,但无论如何,这段代码片段绝对对我最有效。谢谢! - Jim G.
@JimG:很高兴我能帮得上忙 :-) - gen_Eric
1
@JimG 你得到的未定义值是因为在数组元素被切出后,索引发生了变化,所以被接受的答案实际上并不起作用。你能把它改成这个吗? - theringostarrs
1
@GX:你能否将被接受的答案更改为这个答案? - Jim G.
2
提醒一下,如果你要删除的 JSON 对象属性值是一个数字(例如:{"key": 1}),请确保将传递给函数的参数转换为数字:removeValue('key', +value);。这个问题让我疯了几个小时。 - Mohammad Sepahvand

22

试一下这个:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });

5
值得注意的是,它不支持IE < 9(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility) - Jeremy
@Jeremy Heiler:对于IE浏览器,可以从此处提供的代码中添加该功能:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter - c-smile
4
你引用了和我一样的链接 :-P - Jeremy

2
尝试这个。(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

1
您可以通过1个或多个属性进行删除:
//Delets an json object from array by given object properties. 
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); -> 
//removes all items        with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
    var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
    var deleted = 0;
    for (var i = 0, count = indexes.length; i < count; i++) {
        this.splice(indexes[i], 1);
        deleted++;
    }
    return deleted;
}

0

你可以使用_.pullAllBy来完成。

var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];

// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');

// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


0

您可以使用delete运算符通过名称删除属性

delete objectExpression.property

或者遍历对象并找到您需要的值并将其删除:

for(prop in Obj){
   if(Obj.hasOwnProperty(prop)){
      if(Obj[prop] === 'myValue'){
        delete Obj[prop];
      }
   }
}

4
他想从数组中删除整个对象,而不是仅仅删除对象中的某个属性。 - John Strickler

0

接受的答案存在问题,因为它将一个函数附加到了数组原型上。每当您使用 for 循环遍历数组时,该函数都会出现:

for (var key in yourArray) {
    console.log(yourArray[key]);
}

其中一个将出现的值是函数。扩展基本原型的唯一可接受方式(尽管通常不鼓励,因为它会污染全局空间)是使用 .defineProperty 方法:

Object.defineProperty(Object.prototype, "removeValue", {
    value: function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === val) {
                this.splice(i, 1);
                i--;
            }
        }
        return this;
    },
    writable: true,
    configurable: true,
    enumerable: false
});

0

这个只需要JavaScript,看起来比其他答案更易读。 (我假设当你写“value”时,你的意思是“id”)

//your code
var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
    var c, found=false;
    for(c in obj) {
        if(obj[c][prop] == val) {
            found=true;
            break;
        }
    }
    if(found){
        delete obj[c];
    }
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');

//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');

// print our result to console to check it works !
for(c in countries.results) {
    console.log(countries.results[c].id);
}

删除应该仅用于从对象中删除属性,而不是用于删除数组中的元素 - 它仅将该索引处的值替换为未定义!(不会更改数组的长度等)。请参见http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript#comment20295018_5767335。 - Aaron_H

0

这对我有用。

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接