title: Delete object or nested object from array
body: <p>I need to delete an object or nested object in an array, from a given object ID.</p>
  
  <p>The object needed to be deleted can both be a root object in the array or a nested object (a variant in this example) in one of the root objects.</p>
  
  <p>Here's the array structure (both root objects and variant objects has unique IDs):</p>
  
  <pre><code>[
     { id: 1, title: 'object without variants', variants: [] },
     { id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]
  ]
  </code></pre>
  
  <p>So for example if the object ID passed from the click event that triggers the delete function is 1, I want to delete the whole root object with the ID of 1 and if the object passed from the click event is 21, I only want to delete the variant with the ID of 21 under the root object with the ID of 2 and not the whole root object.</p>
  
  <p>How can this be done?</p>
  
  <p><strong>UPDATE</strong>
  I got it working by using this code (passedObjectId is the ID of the object to be removed):</p>
  
  <pre><code>array = array.filter(object =&gt; object.id !== passedObjectId);
  
  for (let object of array) {
     object.variants = object.variants.filter(variant =&gt; variant.id !== passedObjectId);
  }
  </code></pre>
  
  <p>I also need to remove the root object from the array if the last variant is removed from the object.</p>
  
  <p>The code below works, but can I make this any prettier without having to use 3 filter() methods?</p>
  
  <pre><code>array = array.filter(object =&gt; object.id !== passedObjectId);
  
  for (let object of array) {
     // Remove the variant from the root object
     object.variants = object.variants.filter(variant =&gt; variant.id !== passedObjectId);
  
     // Remove the root object, if there's no variants left in it
     if (!object.variants.length) {
        array = array.filter(object =&gt; object.id !== passedObjectId);
     }
  }
  </code></pre>
  
  <p><strong>ANOTHER UPDATE</strong></p>
  
  <p>I ended up using this code, that also removes a root object, if the last variant is removed:</p>
  
  <pre><code>array = array.filter(object =&gt; {
     const hasRemovedVariant = object.variants.some(variant =&gt; variant.id === passedObjectId);
  
     if (hasRemovedVariant) {
        object.variants = object.variants.filter(variant =&gt; variant.id !== passedObjectId);
  
        return object.variants.length;
     }
  
     return object.id !== passedObjectId;
  });
  </code></pre>