Open In App

How to use splice on Nested Array of Objects ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Using the splice() method on a nested array of objects in JavaScript allows you to modify the structure of the nested array by adding or removing elements at specified positions.

Accessing the nested array directly

This approach directly accesses the nested array within each object using dot or bracket notation and applies the splice() method to modify the nested array.

Example: The below example implements the splice() method to access the nested array elements in JavaScript.

Javascript




let nestedArray =
[
    {
        id: 1,
        items: [1, 2, 3]
    },
    {
        id: 2,
        items: [4, 5, 6]
    }
];
 
// Removing element at index 1 from the
// nested array within the first object
nestedArray[0].items.splice(1, 1);
console.log(nestedArray);


Output

[ { id: 1, items: [ 1, 3 ] }, { id: 2, items: [ 4, 5, 6 ] } ]

Utilizing a combination of array methods

This approach involves first finding the index of the object containing the nested array using methods like findIndex(), then applying splice() to the nested array within that object.

Example: The below example Utilizes a combination of array methods with array of objects in JavaScript.

Javascript




let nestedArray = [
    {
        id: 1,
        items: [1, 2, 3]
    },
    {
        id: 2,
        items: [4, 5, 6]
    }
];
let index =
    nestedArray.findIndex(
        obj => obj.id === 1);
// Removing element at index 1 from the
// nested array within the object with id 2
if (index !== -1) {
    nestedArray[index].items.splice(1, 1);
}
console.log(nestedArray);


Output

[ { id: 1, items: [ 1, 3 ] }, { id: 2, items: [ 4, 5, 6 ] } ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads