0

The nesting level is always unknown, and children can be either undefined or an array with at least one item. Each key is always unique. This would be an example:

const arr = [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

I'd like to write a function that receives a key to find the element and then updates its children field with the given children array and then returns the whole arr.

// Function that returns arr with updated the target element - how can I write this?
const mysteryFn = (arr, key, childrenToUpdate) => {
 // Do something..

 return arr;
}


const key = 'goc';
const childrenToUpdate = [{
 key: '12345',
}, {
 key: '25221a',
}];

const newArr = mysteryFn(arr, key, childrenToUpdate);

// expected newArr
const newArr= [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
                children: [{
                    key: '12345',
                }, {
                    key: '25221a',
                }],
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

1 Answer 1

1

This can be achieved with recursion.

const mysteryFn = (arr, key, childrenToUpdate) => {
    // if children are undefined
    if (!arr) return;

    // loop over each entry and its children to find 
    // entry with passed key
    arr.forEach((entry) => {
        if (entry.key === key) {
            entry.children = childrenToUpdate;
        }

        // recursive call to traverse children
        mysteryFn(entry.children, key, childrenToUpdate);
    });

    return arr;
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.