从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 官宣新年祝福语简短