Title

在一个复杂的数组对象数据中(嵌套多层),通过key值返回对应的对象

1 方法:

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

 

  

2、方法使用
举个例子:

  let arr =[
      {
        key: 1,
        value: 'a',
        children: null
      },
      {
        key: 2,
        value: 'b',
        children: null
      },
      {
        key: 3,
        value: 'c',
        children: [
          {
            key: 4,
            value: 'c-1',
            children: null
          },
          {
            key: 5,
            value: 'c-2',
            children: null
          },
          {
            key: 6,
            value: 'c-1',
            children: [
              {
                key: 7,
                value: 'c-1-1',
                children: null
              },
              {
                key: 8,
                value: 'c-1-2',
                children: null
              },
            ]
          }
        ]
      }
    ]

 

直接调用传相对应的参数即可:

 

 

posted on 2023-04-12 19:24  chccee  阅读(1342)  评论(0编辑  收藏  举报