Function to find the parent from an array of objects

function findParent(customCategoryListResult, ID) {
        // Key-value pair to check for
        const keyToFind = "internalid";
        const valueToFind = ID;
        var level = { 0: '', 1: '', 2: '' };
        try {
            // Check if the key-value pair exists in the array without a for loop primary level
            var primaryindex = customCategoryListResult.findIndex(obj => {
                obj[keyToFind] === valueToFind;

            });
            if (primaryindex !== -1) {
                level[0] = primaryindex;
                return level;
            }
            // Check if the key-value pair exists in the array without a for loop secondary level
            const secondaryIndex = customCategoryListResult.findIndex(obj1 => {
                return obj1.categories.some(category => (category[keyToFind] === valueToFind)
                );
            });
            if (secondaryIndex !== -1) {
                level[1] = secondaryIndex;
                return level;
            }

            // Check if the key-value pair exists in the array without a for loop secondary level
            const thirdIndex = customCategoryListResult.findIndex(obj2 => {
                return obj2.categories.some(category => {

                    if (category[keyToFind] === valueToFind) {
                        return true;
                    }
                });
            });
            if (thirdIndex !== -1) {
                level[1] = thirdIndex;
                return level;
            }
        } catch (err) {
            log.debug('error ', err);
        }

        return level;

    }

Leave a comment

Your email address will not be published. Required fields are marked *