How can I get key-value pair(s) without displaying function return message in JS

I hava a nested object like:

let menu = {
    vegetarian: {
        vegStarter: {
            plainPizza: 100,
            redChilliPizza: 150,
            cheesePizza: 200,
            capsicumPizza: 160,
            onionPizza: 200,
        },
        vegMainCourse: {
            pepperoniPizza: 150,
            mushroomsPizza: 160,
            extraCheesePizza: 250,
            blackOlivesPizza: 220,
            greenPeppersPizza: 180,
        }
    },
    nonVegetarian: {
        nonVegStarter: {
            supremeMeatPizza: 100,
            meatPizza: 130,
            meatLoversPizza: 160,
            chickenPizza: 200,
            chilliMeatPizza: 200
        },
        nonVegMainCourse: {
            butterMeatPizza: 220,
            spicyChickenPizza: 170,
            seafoodPizza: 300,
            spinachEggPizza: 200,
            eggPizza: 250,
        }
    }
}

And here’s my input for a function:

let getSearchTermtoFindByNameFromNonVegMainCourse = "spinachEggPizza";

Below is the function:

function searchUsingNameFromNonVegMainCourseCategory(mainObject, getSearchTermtoFindByNameFromNonVegMainCourse) {
    let arrOfNonVegMainCourseKeys = [];
    Object.keys(mainObject).forEach(key => {
        if (getSearchTermtoFindByNameFromNonVegMainCourse === ' ') {
            alert("Enter Valid Value.")
        } else {
            if (key !== getSearchTermtoFindByNameFromNonVegMainCourse) {
                } else {
                if (key === getSearchTermtoFindByNameFromNonVegMainCourse && typeof mainObject[key] !== "object") {
                    arrOfNonVegMainCourseKeys = key;
                    document.write(arrOfNonVegMainCourseKeys + " : " + mainObject[key] + "<br>");
                } else {
                    if (typeof mainObject[key] === "object") {
                    searchUsingNameFromNonVegMainCourseCategory(mainObject[key], getSearchTermtoFindByNameFromNonVegMainCourse, arrOfNonVegMainCourseKeys)
                    }
                }
            }
        }
    }); return document.write("No Match Found.");
}
searchUsingNameFromNonVegMainCourseCategory(menu.nonVegetarian.nonVegMainCourse, getSearchTermtoFindByNameFromNonVegMainCourse);

I want to set No Match Found. only when an input gets mismatch in a function. My code is working fine for the same But for a matched input also it’s displaying No Match Found. with result which I don’t want to show obviously. Here’s the output of above written code:

spinachEggPizza : 200
No Match Found.

But I want only spinachEggPizza : 200 to show as output.

What’s going wrong from my side?

60 thoughts on “How can I get key-value pair(s) without displaying function return message in JS”