Convert string into JSON

-2

I have the following object :

1,2,3,4,5,6

I would like to convert it to JSON to retrieve it in php to hold a for loop:

{"id":"1"}
{"id":"2"}
{"id":"3"}
{"id":"4"}
{"id":"5"}
{"id":"6"}

I get this value from bootstrap-multiselect .

Here's an example:

<select id="category" class="form-control" multiple="multiple">
    <option value="1">Aventura</option>
    <option value="2">Comedia</option>
    <option value="3">Ficção</option>
    <option value="4">Drama</option>
    <option value="5">Novela</option>
    <option value="6">Category</option>
</select>

Javascript:

<script>    
    $('#category').click(function() {    
        alert($('#category').val());    
    })
</script>

Example: link

    
asked by anonymous 12.05.2017 / 06:26

2 answers

1

As the example you indicated in JSFiddle , the value you get from select is already a < in> array , so Aline's solution should work:

// Valor que vem do multi-select:
var values = ["1", "2", "3", "4", "5"];

// Cria uma lista de objetos:
var result = [];

values.forEach(function(value) {
  result.push({id: value});
}); 

// Converte o objeto para JSON:
var json = JSON.stringify(result);

// Exibe o resultado em JSON:
console.log(json);

Your result will be a list of objects:

[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]

An alternative is to create only one object and set the list of id to its value:

// Valor que vem do multi-select:
var values = ["1", "2", "3", "4", "5"];

// Cria um objeto de índice "id" e valores "value":
var result = {id: values};

// Converte o objeto para JSON:
var json = JSON.stringify(result);

// Exibe o resultado em JSON:
console.log(json);

The result, in this form, will be:

{"id":["1","2","3","4","5"]}

That in my view would make more sense, but depends on its application.

    
12.05.2017 / 14:06
0

Assuming you have an array of integers then:

var lValoresDoSelect = [1,2,3,4,5];

var lIds = new Array();
$.each(lValoresDoSelect, function(index, obj){
   lIds.push({ id: obj });
});

Assuming you get this information for an element:

var lIds = new Array();
    $.each($(".multiselect:selected"), function(index, obj){
       lIds.push({ id: $(obj).text() });
    });
    
12.05.2017 / 13:20