我有以下switch / case语句,它从下面的json对象返回数据。实际上这将是很长的!
Switch语句
switch(val){
case 'chicken':
return json['meat']['main'][val];
break;
case 'beef':
return json['meat']['main'][val];
break
case 'lamb':
return json['meat']['main'][val];
break;
case 'pork':
return json['meat']['main'][val];
break;
default:
return '';
}
json对象
json={
"meat": {
"main": {
"chicken": "Roast chicken and vegetables",
"beef": "Beef and Yorkshire pudding",
"lamb": "Lamb shank with red currant gravy",
"pork": "Pork and apple sauce",
}
}
}
您可以看到,switch语句非常重复,因为每个case语句都返回相同的表达式(尽管在访问对象中的变量键[val]时返回的值将有所不同。
实际上,我的json文件很大,所以我要避免手动为每种肉类(鸡肉,牛肉,羊肉,猪肉)键入一个case语句。相反,我想遍历我的json对象以获取json ['meat'] ['main'] [i](其中i是计数器)中的值来创建每种情况。这可能吗?如果没有,是否有替代方法?
非常感谢!
Katie
这是您需要的吗?
let json = {
"meat": {
"main": {
"chicken": "Roast chicken and vegetables",
"beef": "Beef and Yorkshire pudding",
"lamb": "Lamb shank with red currant gravy",
"pork": "Pork and apple sauce",
}
}
}
const search = (obj, val) => {
const keys = Object.keys(obj)
for (const key of keys) {
if (typeof obj[key] === 'string') {
if (key === val) {
return obj[key]
}
} else {
const description = search(obj[key], val)
if (description) {
return description
}
}
}
return ''
}
const description = search(json, 'beef')
console.log(description)