Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

javascript - Creating an array and combining keys

How can amend how items are pushed into a jQuery array? This is the code I'm using at the moment:

   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);

This outputs:

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

How can I output in the following instead?

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

Line 2 doesn't have a variation.

question from:https://stackoverflow.com/questions/65904045/creating-an-array-and-combining-keys

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can try this :

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);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...