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.
javascript object
add a comment |
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.
javascript object
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51
add a comment |
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.
javascript 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.
javascript object
javascript object
edited Dec 18 '18 at 19:32
Peter Mortensen
13.8k1987113
13.8k1987113
asked Dec 18 '18 at 11:13
Michael PhilipsMichael Philips
625722
625722
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51
add a comment |
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51
add a comment |
5 Answers
5
active
oldest
votes
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; }
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
add a comment |
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]);
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of0-0-1
change in length / depth?
– Stuart
Dec 18 '18 at 11:29
add a comment |
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);
add a comment |
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"));
If the path is going to be composed of maybe less than 3 parts you can adjust the function deleteByPath
to handle cases based on number of parts.
if the path is going to be arbitrary and can have any length you can adjust the deleteByPath
function to be recursive like the following:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
add a comment |
//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));
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53831793%2fdeleting-from-an-object-using-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
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; }
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
add a comment |
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; }
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
add a comment |
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; }
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; }
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; }
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; }
answered Dec 18 '18 at 11:19
Nina ScholzNina Scholz
191k15103175
191k15103175
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
add a comment |
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
Wow!!! thanks a lot. Guess I have to do in depth Javascript learning.
– Michael Philips
Dec 18 '18 at 11:33
add a comment |
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]);
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of0-0-1
change in length / depth?
– Stuart
Dec 18 '18 at 11:29
add a comment |
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]);
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of0-0-1
change in length / depth?
– Stuart
Dec 18 '18 at 11:29
add a comment |
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]);
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]);
answered Dec 18 '18 at 11:18
StuartStuart
5,25021530
5,25021530
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of0-0-1
change in length / depth?
– Stuart
Dec 18 '18 at 11:29
add a comment |
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of0-0-1
change in length / depth?
– Stuart
Dec 18 '18 at 11:29
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]);
– Michael Philips
Dec 18 '18 at 11:29
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]);
– Michael Philips
Dec 18 '18 at 11:29
Does your string of
0-0-1
change in length / depth?– Stuart
Dec 18 '18 at 11:29
Does your string of
0-0-1
change in length / depth?– Stuart
Dec 18 '18 at 11:29
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
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);
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);
answered Dec 18 '18 at 11:25
Shubham KhatriShubham Khatri
91.5k15112153
91.5k15112153
add a comment |
add a comment |
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"));
If the path is going to be composed of maybe less than 3 parts you can adjust the function deleteByPath
to handle cases based on number of parts.
if the path is going to be arbitrary and can have any length you can adjust the deleteByPath
function to be recursive like the following:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
add a comment |
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"));
If the path is going to be composed of maybe less than 3 parts you can adjust the function deleteByPath
to handle cases based on number of parts.
if the path is going to be arbitrary and can have any length you can adjust the deleteByPath
function to be recursive like the following:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
add a comment |
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"));
If the path is going to be composed of maybe less than 3 parts you can adjust the function deleteByPath
to handle cases based on number of parts.
if the path is going to be arbitrary and can have any length you can adjust the deleteByPath
function to be recursive like the following:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}
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"));
If the path is going to be composed of maybe less than 3 parts you can adjust the function deleteByPath
to handle cases based on number of parts.
if the path is going to be arbitrary and can have any length you can adjust the deleteByPath
function to be recursive like the following:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}
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"));
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"));
edited Dec 18 '18 at 11:36
answered Dec 18 '18 at 11:22
Nikos M.Nikos M.
4,54521825
4,54521825
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
add a comment |
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
No, path can be of any length :)
– Michael Philips
Dec 18 '18 at 11:24
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
@MichaelPhilips, updated answer to handle path of 1,2 or 3 parts. You can add more cases as needed by example
– Nikos M.
Dec 18 '18 at 11:28
add a comment |
//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));
add a comment |
//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));
add a comment |
//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));
//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));
//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));
//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));
answered Dec 18 '18 at 12:04
Yishai LandauYishai Landau
542312
542312
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53831793%2fdeleting-from-an-object-using-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Have a look at Convert JavaScript string in dot notation into a reference to the object
– Bergi
Dec 18 '18 at 20:51