dcp3450
dcp3450

Reputation: 11187

Removing an object from a nested array if you know the specific location, javascript

I have a nested array of objects. Something like:

[
  {
    item: 'x',
    data: [
      item: 'y',
      data: [
        item: 'z',
        data: [...]
      ]
    ],
    ...
  }
]

I know the item I want to remove is located at position [1, 3, 1, 4]. Is there a faster way to remove that item in the array?

Upvotes: 0

Views: 25

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

Here is an example of how I would do it. I'm retrieving a pointer to the very array to mutate, then I mutate it.

What this code doesn't do is :

  • Doesn't handle the case the given value is incorrect (bad indexes)
  • The keys doesn't exists

What does this code do :

  • Handle the case we remove the first item or a deep item
  • Handle X nested levels
  • mutate the given object

const arr = [{
  item: 'x',
  data: [{
      item: 'y',
      data: [{
        item: 'z',
        data: [],
      }],
    },
    {
      item: 'y2',
      data: [{
        item: 'z',
        data: [{
          item: 'a',
          data: [],
        }, {
          item: 'b',
          data: [],
        }, {
          item: 'toRemove',
          data: [],
        }],
      }],
    }, {
      item: 'y3',
      data: [{
        item: 'z',
        data: [],
      }],
    },
  ],
}];

// /!\ Mutate the given object
function removeAtPos(obj, pos) {
  // Because we look for a pointer, we dont go all in
  // or we would mutate a copy of the data and not the given object data
  const allExceptLast = pos.slice(0, pos.length - 1);

  // ternary is here to handle the case if we have the first item or not
  // First item doesn't start with 'data'
  const ptr = allExceptLast.reduce((tmp, x) => tmp.data ?
                                               tmp.data[x] :
                                               tmp[x], obj);
  
  // Finally remove the wanted part of the array
  (ptr.data || ptr).splice(pos[pos.length - 1], 1);
}

removeAtPos(arr, [0, 1, 0, 2]);

console.log(arr);

Upvotes: 2

Related Questions