2

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"]}]
3
  • Please post the JSON data. Commented Jan 19, 2019 at 8:46
  • What is the content of $("#db_fields")? Commented Jan 19, 2019 at 8:48
  • $.each() with (only) an id should ring all your alarm bells as ids have to be unique. Commented Jan 19, 2019 at 8:48

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.