简体   繁体   English

如何在 JS 中不显示 function 返回消息的情况下获取键值对

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

I hava a nested object like:我有一个嵌套的 object 像:

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:这是我对 function 的输入:

let getSearchTermtoFindByNameFromNonVegMainCourse = "spinachEggPizza";

Below is the function:下面是 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.我想设置No Match Found. only when an input gets mismatch in a function.仅当 function 中的输入不匹配时。 My code is working fine for the same But for a matched input also it's displaying No Match Found.我的代码同样适用,但对于匹配的输入,它也显示未No Match Found. with result which I don't want to show obviously.结果我不想明显地展示出来。 Here's the output of above written code:这是上面编写的代码的output:

spinachEggPizza : 200
No Match Found.

But I want only spinachEggPizza: 200 to show as output.但我只希望spinachEggPizza: 200显示为 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:那是因为你总是在 function 块的底部返回 ""document.write("No Match Found.")"",你可以设置在条件 else 块中打印该消息:

 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.要遍历嵌套的 object 并使用递归查找特殊内容,我们可以使用一个小技巧。

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.我们将一个空数组传递给我们的 function 和 function ,只要我们遇到我们正在寻找的密钥,我们只需将 append 传递给数组。

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."); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当在数组中找到某个键​​值对时,如何返回步骤号 [i]? - How can I return the step number [i] when a certain key-value pair is found in an array? 如何将函数添加为对象中的键值对? - How can a function be added as a key-value pair in an object? 我可以将 function 存储在键值对中,其中 function 是 JavaScript 的键吗? - Can I store function in key-value pair where the function is the key for JavaScript? 无法使用 [FromBody] 获取键值对的值 - Can not get a value of key-value pair using [FromBody] 如何在 javascript 中获取对象数组(键值对)的值? - How to get a value of array of objects (pair key-value) in javascript? JS或jQuery如何删除键值对 - JS or jQuery how to delete key-value pair 如何在对象构造函数的键值对中包含先前声明的函数作为值? - How do I include a previously declared function as a value in a key-value pair in an object constructor? 如何使用CouchDB / Node.js中的Cradle删除键值对? - How do I delete a key-value pair using Cradle in CouchDB/Node.js? 如何使用Cradle将新的键值对添加到CouchDB? Node.js - How do I add a new key-value pair to CouchDB using Cradle? Node.js 如何在JavaScript过滤器函数中访问键值对中的数组 - How to access an array in key-value pair in a javascript filter function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM