I want to get the JSON from an array with this format
[
{
"title": "Name"
},
{
"title": "Phone"
},
{
"title": "Parent Phone"
},
{
"title": "Street"
}
]
I tried this code:
var favorite = new Array();
$.each($("#db_fields"), function() {
var field = {
'title': $(this).val()
};
favorite.push(field);
});
var myJsonString = JSON.stringify(favorite);
alert(myJsonString);
$("#db_fields") is a select (Bootstrap-select), it's an array of string
<select class="form-control" name="db_fields[]" id="db_fields" data-live-search="true" multiple >
<option value="Arabic Name"> Arabic Name</option>
<option value="Building"> Building</option>
</select>
but I got this result
[{"title":["Arabic Name","Phone","Building","Nationality"]}]
Klaus Gütter
12.2k7 gold badges35 silver badges43 bronze badges
1 Answer 1
Iterate through the options of the select ("#db_fields > option") tag:
var favorite = [];
$.each($("#db_fields > option"), function(){
let field = {
'title': this.value
};
favorite.push(field);
});
var myJsonString = JSON.stringify(favorite);
console.log(myJsonString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" name="db_fields[]" id="db_fields" data-live-search="true" multiple >
<option value="Arabic Name"> Arabic Name</option>
<option value="Building"> Building</option>
</select>
answered Jan 19, 2019 at 8:58
Amardeep Bhowmick
17k3 gold badges33 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
$("#db_fields")?$.each()with (only) an id should ring all your alarm bells as ids have to be unique.