Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting from an object using JavaScript

I have an object as shown:

const arr = [
  {
    name: 'FolderA',
    child: [
      {
        name: 'FolderB',
        child: [
          {
            name: 'FolderC0',
            child: [],
          },
          {
            name: 'FolderC1',
            child: [],
          },
        ],
      },
    ],
  },
  {
    name: 'FolderM',
    child: [],
  },
];

And I have path as string:

var path = "0-0-1".

I have to delete the object:

{
    name: 'FolderC1',
    child: [],
 },

Which I can do so by doing,

arr[0].child[0].splice(1, 1);

But I want to do it dynamically. Since path string can be anything, I want the above '.' operator and splice definition to be created dynamically to splice at particular place.

like image 380
Michael Philips Avatar asked Dec 18 '18 11:12

Michael Philips


People also ask

How can I delete a property in an object in JavaScript?

The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

How do you delete an element from an object?

Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.

How do I remove a field from an object in TypeScript?

To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.


2 Answers

You could reduce the indices by saving the last index and returning the children of the actual index. Later splice with the last index.

function deepSplice(array, path) {
    var indices = path.split('-'),
        last = indices.pop();

    indices
        .reduce((a, i) => a[i].child, array)
        .splice(last, 1);
}

const array = [{ name: 'FolderA', child: [{ name: 'FolderB', child: [{ name: 'FolderC0', child: [] }, { name: 'FolderC1', child: [] }] }] }, { name: 'FolderM', child: [] }];

deepSplice(array, "0-0-1");
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 106
Nina Scholz Avatar answered Oct 22 '22 03:10

Nina Scholz


You could split your path and use the parts, like so:

let path = '0-0-1';
let parts = path.split('-');

// Call your splice using your parts (unsure if your '1' is the index, or deleteCount).

// If parts[2] is the index
arr[parts[0]].child[parts[1]].splice(parts[2], 1);

// If parts[2] is the deleteCount:
arr[parts[0]].child[parts[1]].splice(1, parts[2]);
like image 31
Stuart Avatar answered Oct 22 '22 01:10

Stuart