如何使用jquery将表单输入字段转换为嵌套的json结构

时间:2015-09-15 06:35:35

标签: javascript jquery html json angularjs

我想将以下输入字段转换为嵌套的json文件结构,如下所示在我的html页面中,我尝试了几种方法,但无法获得。在这里,我通过angularjs ng-repeat获得这些输入。请帮助我,我该如何实施。提前谢谢。

col

正如我在普通的json结构中得到的那样:

<form id="text" method="post" action="" enctype="multipart/form-data">
    <input type="hidden" value="/images/Image1.nii" name="imageurl">
    <input type="hidden" value="3d0"  name="3d" >
    <input type="hidden" value="sliceX0" name="sliceX"> 
    <input type="hidden" value="sliceY0" name="sliceY">
    <input type="hidden" value="sliceZ0" name="sliceZ">

    <input type="hidden" value="/images/Image2.nii" name="imageurl">
    <input type="hidden" value="3d1"  name="3d1" >
    <input type="hidden" value="sliceX1" name="sliceX"> 
    <input type="hidden" value="sliceY1" name="sliceY">
    <input type="hidden" value="sliceZ1" name="sliceZ">

</form>

但我需要如下:

[{"name":"imageurl","value":"/images/Image1.nii"},{"name":"3d","value":"3d0"},{"name":"sliceX","value":"sliceX0"},{"name":"sliceY","value":"sliceY0"},{"name":"sliceZ","value":"sliceZ0"},{"name":"imageurl","value":"/images/Image2.nii"},{"name":"3d","value":"3d1"},{"name":"sliceX","value":"sliceX1"},{"name":"sliceY","value":"sliceY1"},{"name":"sliceZ","value":"sliceZ1"}]

如何使用jquery

将表单输入字段转换为嵌套的json结构

2 个答案:

答案 0 :(得分:1)

您应该使用lodash之类的帮助程序库来执行此类数据操作。

这是我用lodash做的转换:

// split the data into chunks of 5 elements each
var chunks = _.chunk(data, 5);

// for every chunk create the desired object with the parts
var desired = _.map(chunks, function(c) {
  var image = c[0];
  image.parts = _.rest(c);
  return image;
});

console.log(desired);

这是一个有效的Plunker

答案 1 :(得分:0)

您应该将每个图像组包装在自己的容器中。但是如果你必须保持目前的结构:

var el = document.querySelectorAll('#text [type="hidden"]');

var arr = [];

var obj = {};

var push = false;

for(var i = 0; i < el.length; i ++){

    if(el[i].value.indexOf('images') > -1){
        if(push){
            arr.push(obj);
            obj = {};
         };
        obj.name = 'imageurl';
        obj.value = el[i].value;
        push = true;
    }

    obj.parts = obj.parts || [];

    obj.parts.push({
        name: el[i].name,
        value: el[i].value
    });
}