从数组中删除所有特定对象

时间:2016-11-08 05:55:08

标签: javascript

给定数组:

myArr = [
  {'a':1},
  {'b':1},
  {'b':2},
  {'a':1},
  {'b':2}
]

索引0,其对象为{'a':1},我想取回数组: [{'b':1},{'b':2},{'b':2}]保留原始排序顺序。

即删除索引0中的对象以及所有其他等效对象。  有优雅的方式吗?

3 个答案:

答案 0 :(得分:4)

如果你想删除同一个对象,很简单:



    a1 = { a: 1 }
    b1 = { b: 1 }
    b2 = { b: 2 }
    myArr = [ a1, b1, b2, a1, b2 ]
    
    var filtered = myArr.filter(o => o != a1)
    console.log(filtered);
    // [ {b: 1}, {b: 2}, {b: 2} ]




但是,如果要删除等效对象,则会变得复杂,因为默认情况下JavaScript没有对象等效性测试。您可以自己实现一个,也可以依赖其中一个库,如lodash:



var myArr = [
  {'a':1},
  {'b':1},
  {'b':2},
  {'a':1},
  {'b':2}
];

var filtered = _.filter(myArr, o => !_.isEqual(o, {a: 1}));
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
&#13;
&#13;
&#13;

然后再说一遍,如果你正在使用lodash,你也可以在最大程度上使用它:

&#13;
&#13;
var myArr = [
  {'a':1},
  {'b':1},
  {'b':2},
  {'a':1},
  {'b':2}
];

var filtered = _.differenceWith(myArr, [{a: 1}], _.isEqual);
console.log(filtered);
// [ {b: 1}, {b: 2}, {b: 2} ]
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
&#13;
&#13;
&#13;

基本上做同样的事情,但更容易阅读。

答案 1 :(得分:0)

这对我有用

myArr = [
          {'a':1},
          {'b':1},
          {'b':2},
          {'a':1},
          {'b':2}
        ]

        //Get first item
        for(var key in myArr[0]){
            var firstItem = key;
        }
        alert('First item: ' + firstItem);

        //Remove matches
        var removedItems = []; //Not needed, just used to show you what it's removing.

        myArr.forEach(function(item){
            for (var key in item){
                if(key == firstItem){
                    removedItems.push(key); //Not needed
                    myArr.splice(item, 1); //Remove the array entry
                }
            }
        });
        alert('Removed items: ' + removedItems);

答案 2 :(得分:-3)

尝试myArr.shift();

它将返回{'a':1}

myArr将为[{'b':1},{'b':2},{'b':2}]