Delete object or nested object from array
I need to delete an object or nested object in an array, from a given object ID.
The object needed to be deleted can both be a root object in the array or a nested object (a variant in this example) in one of the root objects.
Here's the array structure (both root objects and variant objects has unique IDs):
[
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]
]
So for example if the object ID passed from the click event that triggers the delete function is 1, I want to delete the whole root object with the ID of 1 and if the object passed from the click event is 21, I only want to delete the variant with the ID of 21 under the root object with the ID of 2 and not the whole root object.
How can this be done?
UPDATE
I got it working by using this code (passedObjectId is the ID of the object to be removed):
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
}
I also need to remove the root object from the array if the last variant is removed from the object.
The code below works, but can I make this any prettier without having to use 3 filter() methods?
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
// Remove the variant from the root object
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
// Remove the root object, if there's no variants left in it
if (!object.variants.length) {
array = array.filter(object => object.id !== passedObjectId);
}
}
ANOTHER UPDATE
I ended up using this code, that also removes a root object, if the last variant is removed:
array = array.filter(object => {
const hasRemovedVariant = object.variants.some(variant => variant.id === passedObjectId);
if (hasRemovedVariant) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
return object.variants.length;
}
return object.id !== passedObjectId;
});
javascript arrays ecmascript-6
add a comment |
I need to delete an object or nested object in an array, from a given object ID.
The object needed to be deleted can both be a root object in the array or a nested object (a variant in this example) in one of the root objects.
Here's the array structure (both root objects and variant objects has unique IDs):
[
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]
]
So for example if the object ID passed from the click event that triggers the delete function is 1, I want to delete the whole root object with the ID of 1 and if the object passed from the click event is 21, I only want to delete the variant with the ID of 21 under the root object with the ID of 2 and not the whole root object.
How can this be done?
UPDATE
I got it working by using this code (passedObjectId is the ID of the object to be removed):
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
}
I also need to remove the root object from the array if the last variant is removed from the object.
The code below works, but can I make this any prettier without having to use 3 filter() methods?
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
// Remove the variant from the root object
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
// Remove the root object, if there's no variants left in it
if (!object.variants.length) {
array = array.filter(object => object.id !== passedObjectId);
}
}
ANOTHER UPDATE
I ended up using this code, that also removes a root object, if the last variant is removed:
array = array.filter(object => {
const hasRemovedVariant = object.variants.some(variant => variant.id === passedObjectId);
if (hasRemovedVariant) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
return object.variants.length;
}
return object.id !== passedObjectId;
});
javascript arrays ecmascript-6
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
1
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25
add a comment |
I need to delete an object or nested object in an array, from a given object ID.
The object needed to be deleted can both be a root object in the array or a nested object (a variant in this example) in one of the root objects.
Here's the array structure (both root objects and variant objects has unique IDs):
[
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]
]
So for example if the object ID passed from the click event that triggers the delete function is 1, I want to delete the whole root object with the ID of 1 and if the object passed from the click event is 21, I only want to delete the variant with the ID of 21 under the root object with the ID of 2 and not the whole root object.
How can this be done?
UPDATE
I got it working by using this code (passedObjectId is the ID of the object to be removed):
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
}
I also need to remove the root object from the array if the last variant is removed from the object.
The code below works, but can I make this any prettier without having to use 3 filter() methods?
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
// Remove the variant from the root object
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
// Remove the root object, if there's no variants left in it
if (!object.variants.length) {
array = array.filter(object => object.id !== passedObjectId);
}
}
ANOTHER UPDATE
I ended up using this code, that also removes a root object, if the last variant is removed:
array = array.filter(object => {
const hasRemovedVariant = object.variants.some(variant => variant.id === passedObjectId);
if (hasRemovedVariant) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
return object.variants.length;
}
return object.id !== passedObjectId;
});
javascript arrays ecmascript-6
I need to delete an object or nested object in an array, from a given object ID.
The object needed to be deleted can both be a root object in the array or a nested object (a variant in this example) in one of the root objects.
Here's the array structure (both root objects and variant objects has unique IDs):
[
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]
]
So for example if the object ID passed from the click event that triggers the delete function is 1, I want to delete the whole root object with the ID of 1 and if the object passed from the click event is 21, I only want to delete the variant with the ID of 21 under the root object with the ID of 2 and not the whole root object.
How can this be done?
UPDATE
I got it working by using this code (passedObjectId is the ID of the object to be removed):
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
}
I also need to remove the root object from the array if the last variant is removed from the object.
The code below works, but can I make this any prettier without having to use 3 filter() methods?
array = array.filter(object => object.id !== passedObjectId);
for (let object of array) {
// Remove the variant from the root object
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
// Remove the root object, if there's no variants left in it
if (!object.variants.length) {
array = array.filter(object => object.id !== passedObjectId);
}
}
ANOTHER UPDATE
I ended up using this code, that also removes a root object, if the last variant is removed:
array = array.filter(object => {
const hasRemovedVariant = object.variants.some(variant => variant.id === passedObjectId);
if (hasRemovedVariant) {
object.variants = object.variants.filter(variant => variant.id !== passedObjectId);
return object.variants.length;
}
return object.id !== passedObjectId;
});
javascript arrays ecmascript-6
javascript arrays ecmascript-6
edited Nov 23 '18 at 13:32
asked Nov 23 '18 at 10:04
Kris D. J.
867
867
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
1
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25
add a comment |
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
1
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
1
1
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25
add a comment |
6 Answers
6
active
oldest
votes
Here is an example on how you can delete them separately, I let you put that together. If you have any question or trouble in the way to do it, feel free to ask.
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
add a comment |
You need to loop through your array and check if each object id is a match if it is the delete the object, else loop through your variants within the object and check for a match and delete the object.
Make sure you loop in reverse as you are modifying the array that you are looping through, hence the indexes change and you might get index out range exception
var myArray = getYourArray();
var idToCheck = 1; // get the id
for(int i=myArray.length;i--){
if(myArray[i].id == idToCheck){
myArray.splice(i);
}
else{
if(myArray[i].variants.length>0){
for(int j=myArray[i].variants.length;j--){
if(myArray[i].variants[j].id == idToCheck){
myArray[i].variants.splice(j);
}
}
}
}
}
add a comment |
This snippet will remove any child with an specified ID, no matter how big the hierarchy is.
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
add a comment |
You need to have a loop inside a loop.
You could use forEach for example.
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
add a comment |
People have already answered but how about some functional, recursive and immutable code:
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
That way if you have some reference to the deleted object, it is deleted in ALL the objects in your array, including any nested variants.
add a comment |
You could create recursive function with some
method so that you can exit the loop on first match and you can use splice
to remove the element.
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
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%2f53444521%2fdelete-object-or-nested-object-from-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is an example on how you can delete them separately, I let you put that together. If you have any question or trouble in the way to do it, feel free to ask.
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
add a comment |
Here is an example on how you can delete them separately, I let you put that together. If you have any question or trouble in the way to do it, feel free to ask.
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
add a comment |
Here is an example on how you can delete them separately, I let you put that together. If you have any question or trouble in the way to do it, feel free to ask.
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
Here is an example on how you can delete them separately, I let you put that together. If you have any question or trouble in the way to do it, feel free to ask.
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
const original = [{
id: 1,
title: 'object without variants',
variants: ,
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1'
}, {
id: 22,
title: 'variant 2'
}],
},
{
id: 3,
title: 'object with one variant',
variants: [{
id: 21,
title: 'variant 1'
}],
}
];
// Remove the root id
const rootIdToDelete = 1;
const modifiedRoot = original.filter(x => x.id !== rootIdToDelete);
// Remove the variant id
const variantToDelete = 21;
const modifiedRootAndVariant = modifiedRoot.filter((x) => {
x.variants = x.variants.filter(x => x.id !== variantToDelete);
// Keep only the roots that have at least 1 variant
return x.variants.length;
});
console.log(modifiedRootAndVariant);
edited Nov 23 '18 at 10:51
answered Nov 23 '18 at 10:09
Grégory NEUT
8,42921437
8,42921437
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
add a comment |
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
1
1
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
This fixed some of my problems, thank you! I also need to delete the root object, if the last variant of the root object is removed - do you have an idea how to do this? :)
– Kris D. J.
Nov 23 '18 at 10:29
1
1
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
@KrisD.J. I've edited my post with one way to do the job
– Grégory NEUT
Nov 23 '18 at 10:52
add a comment |
You need to loop through your array and check if each object id is a match if it is the delete the object, else loop through your variants within the object and check for a match and delete the object.
Make sure you loop in reverse as you are modifying the array that you are looping through, hence the indexes change and you might get index out range exception
var myArray = getYourArray();
var idToCheck = 1; // get the id
for(int i=myArray.length;i--){
if(myArray[i].id == idToCheck){
myArray.splice(i);
}
else{
if(myArray[i].variants.length>0){
for(int j=myArray[i].variants.length;j--){
if(myArray[i].variants[j].id == idToCheck){
myArray[i].variants.splice(j);
}
}
}
}
}
add a comment |
You need to loop through your array and check if each object id is a match if it is the delete the object, else loop through your variants within the object and check for a match and delete the object.
Make sure you loop in reverse as you are modifying the array that you are looping through, hence the indexes change and you might get index out range exception
var myArray = getYourArray();
var idToCheck = 1; // get the id
for(int i=myArray.length;i--){
if(myArray[i].id == idToCheck){
myArray.splice(i);
}
else{
if(myArray[i].variants.length>0){
for(int j=myArray[i].variants.length;j--){
if(myArray[i].variants[j].id == idToCheck){
myArray[i].variants.splice(j);
}
}
}
}
}
add a comment |
You need to loop through your array and check if each object id is a match if it is the delete the object, else loop through your variants within the object and check for a match and delete the object.
Make sure you loop in reverse as you are modifying the array that you are looping through, hence the indexes change and you might get index out range exception
var myArray = getYourArray();
var idToCheck = 1; // get the id
for(int i=myArray.length;i--){
if(myArray[i].id == idToCheck){
myArray.splice(i);
}
else{
if(myArray[i].variants.length>0){
for(int j=myArray[i].variants.length;j--){
if(myArray[i].variants[j].id == idToCheck){
myArray[i].variants.splice(j);
}
}
}
}
}
You need to loop through your array and check if each object id is a match if it is the delete the object, else loop through your variants within the object and check for a match and delete the object.
Make sure you loop in reverse as you are modifying the array that you are looping through, hence the indexes change and you might get index out range exception
var myArray = getYourArray();
var idToCheck = 1; // get the id
for(int i=myArray.length;i--){
if(myArray[i].id == idToCheck){
myArray.splice(i);
}
else{
if(myArray[i].variants.length>0){
for(int j=myArray[i].variants.length;j--){
if(myArray[i].variants[j].id == idToCheck){
myArray[i].variants.splice(j);
}
}
}
}
}
edited Nov 23 '18 at 10:18
answered Nov 23 '18 at 10:12
JustLearning
97921634
97921634
add a comment |
add a comment |
This snippet will remove any child with an specified ID, no matter how big the hierarchy is.
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
add a comment |
This snippet will remove any child with an specified ID, no matter how big the hierarchy is.
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
add a comment |
This snippet will remove any child with an specified ID, no matter how big the hierarchy is.
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
This snippet will remove any child with an specified ID, no matter how big the hierarchy is.
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
var myArray = [{
id: 1,
title: 'object without variants',
variants:
},
{
id: 2,
title: 'object with variants',
variants: [{
id: 21,
title: 'variant 1',
variants: [{
id: 23,
title: 'variant 1'
}, {
id: 24,
title: 'variant 2'
}]
}, {
id: 22,
title: 'variant 2'
}]
}
]
console.log(deleteByID(myArray, 21));
function deleteByID(array, id) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
deleteItemByID(myArray, item, id, i);
}
return array;
}
function deleteItemByID(array, item, id, count) {
if (item.id == id) {
array.splice(count, 1);
return;
} else {
if (item.variants) {
if (typeof item.variants === "object") {
for (var i = 0; i < item.variants.length; i++) {
var varItem = item.variants[i];
deleteItemByID(item.variants, varItem, id, i);
}
}
}
}
}
answered Nov 23 '18 at 10:21
Marius
867
867
add a comment |
add a comment |
You need to have a loop inside a loop.
You could use forEach for example.
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
add a comment |
You need to have a loop inside a loop.
You could use forEach for example.
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
add a comment |
You need to have a loop inside a loop.
You could use forEach for example.
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
You need to have a loop inside a loop.
You could use forEach for example.
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
var arr = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}
];
var idToDelete = 21;
arr.forEach(function(obj,i){
if (obj.id == idToDelete){
arr.splice(i,1);
}
obj.variants.forEach(function(variants,i){
if (variants.id == idToDelete){
obj.variants.splice(i,1);
}
})
})
console.log(arr)
answered Nov 23 '18 at 10:23
Wimanicesir
41610
41610
add a comment |
add a comment |
People have already answered but how about some functional, recursive and immutable code:
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
That way if you have some reference to the deleted object, it is deleted in ALL the objects in your array, including any nested variants.
add a comment |
People have already answered but how about some functional, recursive and immutable code:
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
That way if you have some reference to the deleted object, it is deleted in ALL the objects in your array, including any nested variants.
add a comment |
People have already answered but how about some functional, recursive and immutable code:
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
That way if you have some reference to the deleted object, it is deleted in ALL the objects in your array, including any nested variants.
People have already answered but how about some functional, recursive and immutable code:
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
That way if you have some reference to the deleted object, it is deleted in ALL the objects in your array, including any nested variants.
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
let array = [
{ id: 1, title: 'object without variants', variants: },
{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }] }
];
const deleteFromArray = (arr, id) => {
if (!arr) return
let res = ;
arr.forEach((obj) => {
if (obj.id !== id) {
res.push({ ...obj, variants: deleteFromArray(obj.variants, id) })
}
})
return res;
}
console.log(JSON.stringify(deleteFromArray(array, 1)));
answered Nov 23 '18 at 10:29
osp
1,9091329
1,9091329
add a comment |
add a comment |
You could create recursive function with some
method so that you can exit the loop on first match and you can use splice
to remove the element.
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
add a comment |
You could create recursive function with some
method so that you can exit the loop on first match and you can use splice
to remove the element.
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
add a comment |
You could create recursive function with some
method so that you can exit the loop on first match and you can use splice
to remove the element.
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
You could create recursive function with some
method so that you can exit the loop on first match and you can use splice
to remove the element.
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
const data = [{ id: 1, title: 'object without variants', variants: },{ id: 2, title: 'object with variants', variants: [{ id: 21, title: 'variant 1' }, { id: 22, title: 'variant 2' }]}]
function remove(data, oid) {
data.some((e, i) => {
if(oid == e.id) return data.splice(i, 1);
if(e.variants) remove(e.variants, oid)
})
}
remove(data, 21)
console.log(data)
answered Nov 23 '18 at 10:31
Nenad Vracar
70.2k115678
70.2k115678
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2f53444521%2fdelete-object-or-nested-object-from-array%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
Can you explain more how you'd want to call this function from an on click? Would you be passing in the whole array or a single object?
– Luke Walker
Nov 23 '18 at 10:16
1
This is not a "bring your homework" site. What have you tried?
– hon2a
Nov 23 '18 at 10:25