从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 婆婆高寿祝福语大全简短