从JavaScript中的嵌套JSON对象获取键的值
假设我们有一个嵌套的JSON对象,如下所示:
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};我们需要编写一个JavaScript函数,该函数将一个这样的对象作为第一个参数,并将键字符串作为第二个参数。
然后,我们的函数应返回该特定键属性所属的“值”属性的值。
示例
为此的代码将是-
const obj = {
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
};
const findByKey = (obj, key) => {
const arr = obj['prop'];
if(arr.length){
const result = arr.filter(el => {
return el['key'] === key;
});
if(result && result.length){
return result[0].value;
}
else{
return '';
}
}
}
console.log(findByKey(obj, 'BAR'));输出结果
控制台中的输出将是-
Bar is bad, really bad
热门推荐
10 侄儿高考祝福语简短语
11 搬家寄语祝福语大全简短
12 老婆侄女礼物祝福语简短
13 学生 牛年祝福语大全简短
14 如何送长辈祝福语简短
15 姐妹乔迁贺卡祝福语简短
16 毕业升高中祝福语简短
17 搬迁水果礼盒祝福语简短
18 公司团建周年祝福语简短