JS 数组与字典(JSON)通过字符串快捷取值

134 阅读1分钟
  • 有的情况下,需要通过一个字符串快捷获取到 Json 或 数组Json 中指定对象的值,比如:

    <script>
    
      // -------------------------- Json 测试
    
      // 数据
      const json = {
        a: 'a',
        b: {
          c: 'c',
          d: [{
            e: 'e'
          }],
          f: [[{
            g: 'g'
          }]]
        }
      }
      // 调用
      console.log(GetValue(json, 'b.d[0]')) // {e: 'e'}
      console.log(GetValue(json, 'b.f[0][0].g')) // g
      console.log(GetValue(json, 'b.f[0[0.g')) // g
      console.log(GetValue(json, 'b.f]0]0.g')) // g
      console.log(GetValue(json, 'b.f.0.0.g')) // g
    
      // -------------------------- Array 测试
    
      // 数据
      const arr = [
        {
          a: 'a',
          b: [{
            c: 'c',
            d: {
              e: 'e'
            }
          }]
        }
      ]
      // 调用
      console.log(GetValue(arr, '[0].b[0].d.e')) // e
      console.log(GetValue(arr, '0.b.0.d.e')) // e
    
    </script>
    
  • 封装方法

    <script>
    
      // 获取值
      function GetValue(obj, key) {
        // 当前值
        var value = undefined
        // 是否有值
        if (obj && key) {
          // 赋值
          value = obj
          // 分析大括号
          if (key.includes('[') || key.includes(']')) {
            // 替换符号
            if (key.includes('[')) {
              key = key.replace(new RegExp('\\[', "gm"), '.')
              key = key.replace(new RegExp('\\]', "gm"), '')
            } else {
              key = key.replace(new RegExp('\\]', "gm"), '.')
            }
          }
          // 拆分
          const keys = key.split('.')
          // 过滤出来可用的 keys
          const newKeys = []
          // 过滤
          keys.forEach(itemKey => {
            // 有值则添加
            if (itemKey.length) { newKeys.push(itemKey) }
          })
          // 取值
          newKeys.some(itemKey => {
            // 直接取值
            if (value) { value = value[itemKey] }
            // 是否停止
            return !value
          })
        }
        // 返回
        return value
      }
    
    </script>