0

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

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Accepting this as the answer, as my original question did include lodash
1

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

1 Comment

Just as valid, this is how I normally do things using raw arrays in various languages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.