Deleting from an object using JavaScript

javascript remove object from array
remove element from json object javascript
remove property from array of objects javascript
remove element from object javascript
delete multiple properties from object javascript
javascript delete variable
delete object java
lodash remove key from object

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.

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

delete operator, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

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

Deleting Objects in JavaScript, An object will automatically be deleted when all the references on it are removed. Hence, if you want to remove an object, try DELETING all the objects referencing​  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).

You could write a recursive function which travels down the hierarchy till the path is available. Below is a very minimal snippet.

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

let ar_path = "0-0-1";

function deleteRecursive(arr, path) {
  if(Array.isArray(arr) && path.length > 0){
     const index = Number(path.shift());
     if (path.length > 0) 
        deleteRecursive(arr[index].child, path)
     else 
        arr.slice(index, 1);
  } else {
     console.log('invalid');
  }
}


deleteRecursive(arr, ar_path.split('-'))

console.log(arr);

How To Remove a Property from a JavaScript Object, a JavaScript object. Find out the alternatives and the suggested solution. delete car.brand. Delete a property from an object in JavaScript. Finally, we logged the object to the browser console so that we can see the result. If you run the example above, you should see the following output in your browser console: As you can see, the “email” property has been completely removed from our object. Dynamically deleting a property from a JavaScript object.

If the path is always going to be composed by 3 (or less) indices you can do it easily like the following:

function deleteByPath(arr, path) {
   const index = path.split('-').map((x) => +x);
   if ( index.length < 1) {
      return null;
   } else if ( 1 === index.length ) {
     return arr.splice(index[0], 1);
   } else if ( 2 === index.length ) {
     return arr[index[0]].child.splice(index[1], 1);
   } else {
     return arr[index[0]].child[index[1]].child.splice(index[2], 1);
   }
}

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

console.log(deleteByPath(arr, "0-0-1"));
console.log(deleteByPath(arr, "0-1"));
console.log(deleteByPath(arr, "0"));

How can we destroy an object in javascript?, More specifically, it will delete object properties. For example: var multiverse = { earth1: "Silver Age"  Update and deleting properties from an object in JavaScript Any property can be removed from an object by using delete us to delete and change the value of a property from a Javascript object.

//Variable setup:
const arr = [
    {
        name: 'FolderA',
        child: [
            {
                name: 'FolderB',
                child: [
                    {
                        name: 'FolderC0',
                        child: [],
                    },
                    {
                        name: 'FolderC1',
                        child: [],
                    },
                ],
            },
        ],
    },
    {
        name: 'FolderM',
        child: [],
    },
];
const path = "0-0-1";
//Break the path into pieces to iterate through:
const pathArray = path.split("-");
//Javascript assignments are by reference, so arrayToManage is going to be an internal piece within the original array
let arrayToManage = arr;
//We are going to iterate through the children of the array till we get above where we want to remove
while(pathArray.length > 1){
    const key = parseInt(pathArray.shift());
    arrayToManage = arrayToManage[key].child;
}
//Get the last position of the last array, where we want to remove the item
const key = parseInt(pathArray.shift());
arrayToManage.splice(key,1);
//And because it's all by reference, changed we made to arrayToManage were actually made on the arr object
console.log("end result:", JSON.stringify(arr));

How to remove a property from a JavaScript object, Use this tutorial to delete an property from a javascript object. will help you to remove property of a JavaScript object using 'delete' operator. The remove () method is used to remove an option from a drop-down list. Tip: To add an option to a drop-down list, use the add () method.

The `delete` Operator in JavaScript, In JavaScript, the delete operator is employed to delete a property of an object. After Duration: 12:57 Posted: Feb 10, 2020 Deleting from an object using JavaScript. up vote 10 down vote favorite. 2. I have to delete the object: {name: 'FolderC1', child: ,}, Which I can do so by doing,

How to Remove Property from JavaScript Object – TecAdmin, delete operator only works on configurable objects. delete cannot remove the non-configurable properties of an object. Our obj object was  Select the HTML element which need to remove. Use JavaScript remove () and removeChild () method to remove the element from the HTML document. Example 1: This example uses removeChild () method to remove the HTML element.

5 things you need to know about the delete operator in JavaScript, Otherwise, the client object model does not know the real type of the returned object oField and, by default, uses Field as the object type. Deleting a List Using JavaScript. To delete a list, call the deleteObject() function of the list object, as shown in the following example.

Comments
  • Have a look at Convert JavaScript string in dot notation into a reference to the object
  • This I want to be dynamic, I don't know how long the path nested would be: arr[parts[0]].child[parts[1]].splice(1, parts[2]);
  • Does your string of 0-0-1 change in length / depth?
  • No, path can be of any length :)
  • @MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example