首页 > 解决方案 > 创建数组并组合键

问题描述

如何修改项目被推入 jQuery 数组的方式?这是我目前正在使用的代码:

   var sub_updated = [];
    $('.current-sub-items').each(function() {
        $(this).find('.prod-select').each(function() {
            if($(this).parent().css('display') != 'none'){
                var s_main_prod = $(this).val();
                sub_updated.push({
                    product:s_main_prod,
                });
            }
        });
        $(this).find('.var-select').each(function() {
            if($(this).parent().css('display') != 'none'){
                var s_var_prod = $(this).val();
                sub_updated.push({
                    variation:s_var_prod,
                });
            }
        });
    });
    
    console.log(sub_updated);

这输出:

0: {product: "201"}
1: {variation: "202"}
2: {product: "192"}
3: {variation: "194"}
4: {product: "965"}

我怎样才能在下面输出呢?

0: {product: "201", variation: "202"}
1: {product: "192", variation: "194"}
2: {product: "965"}

第 2 行没有变化。

标签: javascriptjquery

解决方案


你可以试试这个:

var sub_updated = [];
$('.current-sub-items').each(function() {
    var obj = {};
    $(this).find('.prod-select').each(function() {
        if($(this).parent().css('display') != 'none'){
            var s_main_prod = $(this).val();
             if (s_main_prod ){
             obj['product']=s_main_prod
             }
        }
    });
    $(this).find('.var-select').each(function() {
        if($(this).parent().css('display') != 'none'){
            var s_var_prod = $(this).val();
             if (s_var_prod ){
             obj['variation']=s_var_prod
             }
        }
    });
    sub_updated.push(obj);
})

推荐阅读