Deleting from an object using JavaScript

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: