代码之家  ›  专栏  ›  技术社区  ›  vasilenicusor

将json对象结构转换为html输入元素

  •  0
  • vasilenicusor  · 技术社区  · 8 年前

    我需要创建具有name-value的动态隐藏元素来存储json对象。

    对于此输入:

    json_structure = {
        'var_1':'value_1',
        'var_2': {
            'var_2_1':'value_2_1',
            'var_2_2':'value_2_2'
        },
        'var_3': 'value_3'
    };
    

    应该有

    <input type="hidden" name="var_1" value="value_1" />
    <input type="hidden" name="var_2[var_2_1]" value="value_2_1" />
    <input type="hidden" name="var_2[var_2_2]" value="value_2_2" />
    <input type="hidden" name="var_3" value="value_3" />
    

    编辑1 这是我的示例,但仅适用于一级对象。对于多层需要做递归函数来构建entyre结构。

    for(var key in json_structure ) {
            if(json_structure .hasOwnProperty(key)) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", json_structure [key]);
    
                form.appendChild(hiddenField);
             }
        }
    

    有没有一种方法可以在今年发布的javascript或jquery函数中实现这一点?

    提前感谢您!

    2 回复  |  直到 8 年前
        1
  •  3
  •   Pranav C Balan Ansh Takalkar    8 年前

    您可以使用某种递归方法来生成使用 Object.keys 和 Array#forEach 用于迭代对象属性的方法。

    var json_structure = {
      'var_1': 'value_1',
      'var_2': {
        'var_2_1': 'value_2_1',
        'var_2_2': 'value_2_2'
      },
      'var_3': 'value_3'
    };
    
    // function forr generating input
    function genInput(obj, res, prefix) {
      // get all the object keys and iterate
      Object.keys(obj).forEach(function(k) {
        // generate the name with prefix
        var name = prefix ? prefix + '[' + k + ']' : k;
    
        // check property value is object
        // in case its object call the function recursively
        if (typeof obj[k] == 'object')
          // skip null by checking value is truthy
          obj[k] && genInput(obj[k], res, name);
    
        // else generate the input and push into the output array  
        else
          res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>')
      })
    
      // finally return the array generated
      return res;
    }
    
    console.log(
      genInput(json_structure, [])
    )

    要生成DOM元素并进行更新,可以将jQuery与上述代码一起使用,也可以使用纯java进行类似操作。

    var json_structure = {
      'var_1': 'value_1',
      'var_2': {
        'var_2_1': 'value_2_1',
        'var_2_2': 'value_2_2'
      },
      'var_3': 'value_3'
    };
    
    function genInput(obj, form, prefix) {
      Object.keys(obj).forEach(function(k) {
        var name = prefix ? prefix + '[' + k + ']' : k;
        if (typeof obj[k] == 'object') {
          obj[k] && genInput(obj[k], form, name);
        } else {
          var hiddenField = document.createElement("input");
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("name", name);
          hiddenField.setAttribute("value", obj[k]);
          form.appendChild(hiddenField);
        }
      })
    }
    
    genInput(json_structure, document.getElementsByTagName('form')[0])
    <form></form>

    使用jQuery:

    var json_structure = {
      'var_1': 'value_1',
      'var_2': {
        'var_2_1': 'value_2_1',
        'var_2_2': 'value_2_2'
      },
      'var_3': 'value_3'
    };
    
    // function forr generating input
    function genInput(obj, res, prefix) {
      Object.keys(obj).forEach(function(k) {
        var name = prefix ? prefix + '[' + k + ']' : k;
        if (typeof obj[k] == 'object')
          obj[k] && genInput(obj[k], res, name);
        else
          res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>')
      })
      return res;
    }
    
    // append the array of html string
    $('form').append(genInput(json_structure, []))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form></form>
        2
  •  1
  •   timothyclifford    8 年前

    在这种情况下,实际上不需要jQuery。

    这里有一个稍微不同的版本。

    var json_structure = {
        'var_1':'value_1',
        'var_2': {
            'var_2_1':'value_2_1',
            'var_2_2':'value_2_2'
        },
        'var_3': 'value_3'
    };
    
    function createHiddenInput(name, value) {
      var hiddenInput = document.createElement("input");
      hiddenInput.setAttribute("type", "hidden");
      hiddenInput.setAttribute("name", name);
      hiddenInput.setAttribute("value", value);
      document.body.appendChild(hiddenInput);
      console.log(hiddenInput);
    }
    
    function generateInputs(structure, prepend) {
      for (var propertyKey in structure) {
        if (structure.hasOwnProperty(propertyKey)) {
          var property = json_structure[propertyKey]
          if (typeof property === 'object') {
            generateInputs(property, propertyKey)
          } else {
            var name = prepend ? prepend + '[' + propertyKey + ']' : property;
            createHiddenInput(name, propertyKey)
          }
        }
      }
    }
    
    generateInputs(json_structure)
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
    </head>
    <body>
    </body>
    </html>