0

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?

kuldeep
  • 11
  • 2

3 Answers3

1

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.")
        } 
    });
}
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

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; }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
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.");
}
AbbasEbadian
  • 653
  • 5
  • 15
  • Again this is working fine @AbbasEbadian. But by using your logic I'm trying to check from Root i.e. menu and I am getting 'No Match' for a valid input. Actually I want to set this message for all my cases starting from menu. If you want me to share code, I can. – kuldeep Jan 31 '21 at 11:00
  • https://stackoverflow.com/q/65998218/15069520 Again some work for you @AbbasEbadian. I hope you won't mind. – kuldeep Feb 01 '21 at 18:35
  • @kuldeep If my answers Do answer your questions, and are helpful, I will be thankful if you upvote and mark them as accepted answer. – AbbasEbadian Feb 02 '21 at 08:02