Mohamed Fradi
Mohamed Fradi

Reputation: 23

javascript array with key

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"]}]

Upvotes: 2

Views: 70

Answers (1)

Fullstack Guy
Fullstack Guy

Reputation: 16908

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>

Upvotes: 1

Related Questions