【问题标题】:remove item from array using its name / value使用其名称/值从数组中删除项目
【发布时间】:2011-06-10 18:34:45
【问题描述】:

我有以下数组

var countries = {};

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

如何使用它的名称或 id 从这个数组中删除一个项目?

谢谢

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

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

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

    【讨论】:

    • 注意:需要jQuery才能使用此功能
    • 这不会破坏索引,因为如果删除了元素,索引会在执行过程中发生变化。
    • @JohnStrickler:你能在没有 jquery 的情况下重写它吗?我不喜欢图书馆。
    • 根据文档api.jquery.com/each,$.each 不再接受两个参数(不再?)。
    • 谢谢。像魅力一样工作:-)
    【解决方案2】:
    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');
    

    【讨论】:

    • +1:这不是投票最高的答案,但对我来说效果最好。我正在解析从 jquery AJAX 成功处理程序返回的 JSON 数组,并且 $.each 方法意外地绊倒了“未定义”值。我仍然不确定为什么要从一开始就返回“未定义”值;但无论如何,这段代码 sn-p 绝对最适合我。谢谢!
    • @JimG.: 很高兴我能帮上忙 :-)
    • @JimG 您得到的未定义值是因为在拼接出数组元素后索引发生了变化,因此接受的答案实际上不起作用。可以改成这个吗]
    • @GX.: 你能把接受的答案改成这个答案吗?
    • 请注意,如果您要删除的 JSON 对象的属性值是一个数字(例如:{"key": 1}),请确保将您传递的参数转换为函数到一个数字:removeValue('key', +value); 这让我发疯了几个小时。
    【解决方案3】:

    试试这个:

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

    【讨论】:

    【解决方案4】:

    试试这个。(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"]);
    

    【讨论】:

      【解决方案5】:

      您可以删除 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;
      }
      

      【讨论】:

        【解决方案6】:

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

        delete objectExpression.property
        

        或者遍历对象并找到你需要的值并删除它:

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

        【讨论】:

        • 我认为他想从数组中删除整个对象。而不是从对象中删除属性。
        【解决方案7】:

        这只需要 javascript 并且看起来比其他答案更具可读性。 (我假设当你写“价值”时,你的意思是“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);
        }
        

        【讨论】:

        • Delete 只能用于从对象中删除属性,而不是用于删除数组中的内容 - 它只是用未定义的索引替换该索引处的值! (不改变数组的长度等)。见stackoverflow.com/questions/5767325/…
        【解决方案8】:

        它对我有用..

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

        【讨论】:

          【解决方案9】:

          您可以通过 _.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>

          【讨论】:

            【解决方案10】:

            也许这也有帮助。

            for (var i = countries.length - 1; i--;) {
                if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
                    countries.splice(i, 1);
                }
            }
            

            【讨论】:

              【解决方案11】:

              接受的答案是有问题的,因为它将函数附加到 Array 原型。每当您使用 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
              });
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2016-07-24
                • 1970-01-01
                • 1970-01-01
                • 2021-10-19
                • 2022-01-13
                • 2021-10-03
                • 1970-01-01
                相关资源
                最近更新 更多