从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