Blog>
Snippets

Updating Deeply Nested Arrays with Spread Operator

Demonstrate how to update a specific item in a deeply nested array using the spread operator while preserving immutability.
// Given a deeply nested array
const nestedArray = [
    { id: 1, items: ['a', 'b', 'c'] },
    { id: 2, items: ['d', 'e', { sub: ['x', 'y', 'z'] }] },
    { id: 3, items: ['f', 'g', 'h'] }
];

// Suppose we want to update 'y' to 'Y' in the sub-array of the second element
const updatedNestedArray = nestedArray.map(item => {
    if (item.id === 2) {
        return {
            ...item, // Copy the item object
            items: item.items.map(subItem => {
                if (typeof subItem === 'object' && subItem.sub) {
                    // It's the object containing the sub-array
                    return {
                        ...subItem, // Copy the subItem object
                        sub: subItem.sub.map(subValue => subValue === 'y' ? 'Y' : subValue) // Update the sub-array
                    };
                }
                return subItem; // Return the subItem unchanged if it's not the object we're looking for
            })
        };
    }
    return item; // Return item unchanged if it's not the one we're looking for
});

console.log(updatedNestedArray);
This code snippet maps over 'nestedArray' to find the specified object by 'id', then it maps over the 'items' property of that object. When it finds an object within 'items', it checks for the 'sub' property and maps over the 'sub' array to update the targeted value from 'y' to 'Y'. The spread operator is used to create copies at each level of nesting to ensure immutability.