简体   繁体   中英

JavaScript Deleting all objects from an array which contain a value

I have an obj, with an array of objects - something like below (I've not pasted it here because its HUGE). I'm trying to loop through the array of objects - deleting those objects from the array which contain a value. I have written the following code... (using lodash)

When looping over the array its randomly missing a few 'Foo's - so not all the Foo objects are deleted... even though they contain the key Foo. It does ignore that which doesn't contain Foo though.

obj = {
      array : [
         {
          key1 : 'Foo',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi',
          Key3 : 'blah'
         },
         {
          key1 : 'Fred',
          Key2 : 'fi'
         },
         {
          key1 : 'Foo',
          Key2 : 'fi'
         }
         ... etc....
      ]
}

  var items = obj.array
  _.forEach(items, function(n, index) {
   var isFoo = _.includes(n, 'Foo');
   console.log(isFoo);
   if (isFoo) {
      items.splice(index, 1);
    }
  });

I suspect things are getting confused because you are changing the array at the same time as you are looping through it.

_.remove is probably a better option for you here:

 var obj = { array : [ { key1 : 'Foo', Key2 : 'fi' }, { key1 : 'Foo', Key2 : 'fi', Key3 : 'blah' }, { key1 : 'Fred', Key2 : 'fi' }, { key1 : 'Foo', Key2 : 'fi' } ] }; _.remove(obj.array, function(n, index) { return _.includes(n, 'Foo'); }); console.dir(obj.array) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script> 

I ditched lodash, and just did a reverse for-loop (my thinking was that as things were being removed, the index would change... and maybe that was causing the errors?)

var items = obj.array;
var i;
for (i = items.length - 1; i >= 0; i -= 1) {
    if (items[i].type === 'Foo') {
        items.splice(i, 1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM