[英]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.