简体   繁体   中英

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?

That's because you are always returning ""document.write("No Match Found.")"" at the bottom of function block, you can set to print that message inside a conditional else block:

 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) } } } else { document;write("No Match Found.") } }); }

why not simply do:

 const 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 } } } function foo(path, prop ) { let res = null try { res = path[ prop ] } catch(e) { alert("Enter Valid Value.") return null } return (res==undefined)? 'No Match Found.': `${prop}: ${res}` } console.log( foo(menu.nonVegetarian.nonVegMainCourse, 'spinachEggPizza') )
 .as-console-wrapper { max-height: 100%;important: top; 0; }

To traverse a nested object and look for something special using recursion, there is a little trick which we can use.

We pass an empty array to our function and inside the function whenever we meet the key that we are looking for,we just append it to the array.

Finally return that array as result.

 function searchPrice(mainObject, search_text, found_prices) { Object.keys(mainObject).forEach(key => { if (typeof mainObject[key] == "object"){ // Note that we pass found_prices here as well searchPrice(mainObject[key], search_text, found_prices); }else{ if (key === search_text) { // if found, push price to found_prices found_prices.push(mainObject[key]); } } }); return found_prices } 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, } } } let search_text = 'spinachEggPizza'; // Pass an empty array to function which will be filled with price or prices of matching keys let prices = searchPrice(menu, search_text, []); // If any prices were found then we print them out if (prices.length > 0){ prices.forEach(price => { document.write(search_text + ": " + price+ "<br>"); }); }else{ document.write("No Match."); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM