Creating json array using javascript

I want to create a json string based on a button selection on an html page.

<div id="btnStudios" >
<button type="button" id="01" value="warner" class="btn btn-default">Warner</button>
<button type="button" id="02" value="tf1" class="btn btn-default">TF1</button>
<button type="button" id="03" value="gaumont" class="btn btn-default">Gaumont</button>
<button type="button" id="04" value="pathe" class="btn btn-default">Pathe</button>
<button type="button" id="05" value="studiocanal" class="btn btn-default">StudioCanal</button>
<button type="button" id="06" value="francetv" class="btn btn-default">FranceTV</button>
<button type="button" id="07" value="m6snd" class="btn btn-default">M6SND</button>
</div>

<div id = "btnplatforms" class="btn-group">
<button type="button" id = "11" value="orange" class="btn btn-default">Orange</button>
<button type="button" id = "12" value="itunes" class="btn btn-default">iTunes</button>
<button type="button" id = "13" value="sfr" class="btn btn-default">SFR</button>
</div>

$(".btn").click(function() {
$(this).toggleClass('active');
});

Depending on the active state of the button, I want the result to be, for example, {Studios: Warner, Gaumont Platform: orange, iTunes}

Is it possible to achieve this with javascript? If so, how? Thanks in advance for your help.

+4
source share
2 answers

You can try the following:

var output = {
    Studios: $('#btnStudios button.active').map(function() {
        return $(this).val();
    }).get(),
    Platform: $('#btnplatforms button.active').map(function() {
        return $(this).val();
    }).get()
};

here is jsFiddle .

+2
source

You can try the following:

   var btn_active_array = {
    "Studios" : [],
    "Platform":[]
   };


   $('#btnStudios .btn.active').each(function(index,btn_active){
       btn_active_array["Studios"].push($(btn_active).text());
   });
   $('#btnplatforms .btn.active').each(function(index,btn_active){
       btn_active_array["Platform"].push($(btn_active).text());
   });

jsfiddle link: https://jsfiddle.net/5kb5fdyz/

+3
source

All Articles