jQuery - 来自多个来源的数组

时间:2017-02-24 09:57:49

标签: jquery

我无法弄清楚如何从多个来源创建JSON对象。 我的意思是,多个字段和下拉列表,一个输入多个文件,每个文件下面一个下拉大小,第二个有数量,另一个有纸张类型。

我需要将关于每个文件的所有这些信息放在这样的对象中:

{
  "files": [
    {"file_name" : "file1", "size" : "10x10", "quantity" : 1, "paper" : "glossy"},
    {"file_name" : "file2", "size" : "10x10", "quantity" : 4, "paper" : "glossy"},
    {"file_name" : "file3", "size" : "20x30", "quantity" : 3, "paper" : "glossy"},
    {"file_name" : "file4", "size" : "30x40", "quantity" : 6, "paper" : "glossy"},
    {"file_name" : "file5", "size" : "20x30", "quantity" : 2, "paper" : "glossy"},
  ]
}

我有代码,但它不起作用,因为有两个不同的数组。我试图在一个数组中推送数据,但结果对象的结构是错误的。

    function addToPhotoArray() {
        PhotoArray = [];
        var items = $('input[name*=files]')[0].files;
        var filesLength = $('input[name*=files]')[0].files.length;
        if (filesLength > 0) {
            for (var i = 0; i < filesLength; i++) {
                var fileName = items[i].name;
                PhotoArray.push({ name: fileName });
                console.log(fileName);
            }
        }
    }

    function addToCountArray() {
        CountArray = [];
        $('.photo_count option:selected').each(function(){
            CountArray.push({ photo_count: $(this).val() });
        });
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

你在找这样的东西吗?

这样更好吗?

var jsonArr = [];
var json = "[]";

function createJson(){
    jsonArr = JSON.parse(json);

    $(".file_container").each(function(index, container){
        if($(container).find("input[type='file']").val() != ''){
            jsonArr.push(new File(
                $(container).find("input[type='file']").val().replace(/C:\\fakepath\\/i, ''),
                $(container).find("select#size").val(),
                $(container).find("select#count").val(),
                $(container).find("select#paper").val()
            ));
        }
    });


    json = JSON.stringify(jsonArr);
}

function File(file_name, size, quantity, paper){ //class
        this.file_name = file_name;
    this.size = size;
    this.quantity = quantity;
    this.paper = paper;
}
相关问题