根据key查找对象数组中符合的一项 返回对象(递归)

function parseJson(jsonObj, key, value) {
      // 循环所有键
      let array = []
      for (let v in jsonObj) {
        let element = jsonObj[v]
        // 1.判断是对象或者数组
        if (typeof (element) == 'object') {
          let result =  parseJson(element, key, value)
          if(result) return result
        } else {
          if (v == key) {
            if (element == value) return jsonObj
          }
        }
      }
    }

    var array = [
      {
        code: 1,
        value: 'b'
      },
      {
        code: 2,
        value: 'a'
      },
      {
        code: 3,
        value: 'c'
      },
      {
        code: 4,
        value: 'd'
      },
      {
        code: 5,
        value: 'e'
      },
      {
        code: 5,
        value: 'f'
      }
    ]

    console.log(parseJson(array, 'code', 5))

原文地址:https://www.cnblogs.com/likewpp/p/11770772.html