Change format of value in input from AJAX request

Viewed 115

I have a data variable holding an object like this:

{
  "details": {
    "id": 10,
    "name": John Doe,
    "hobbies": [{
        "id": 1,
        "name": "Football"
      },
      {
        "id": 2,
        "name": "Badminton"
      },
      {
        "id": 3,
        "name": "Running"
      }
    ],
    "dob": 1989-12-31
  }
}

I retrieve it using this AJAX request:

$.ajax({
  type: 'POST',
  url: "{{ route('askdata') }}",
  dataType: 'json',
  data: { 'id': $('#member_id').val(), },
  success: function(data) {
    $('#id').val(data.details.id);
    $('#name').val(data.details.name);
    $('#dob').val(data.details.dob);
    $('#hobbies').val(JSON.stringify(data.details.hobbies, ['name']));
  }
});

I get a value in the hobbies input like this:

[{"name":"Football"},{"name":"Badminton"},{"name":"Running"}]

How can I change this to get the values like Football, Badminton, Running?

2 Answers

Your current logic is building a JSON string from the hobbies array. To get the output you want you can use map() to build an array of the hobby names which you can then join() together to form a single string:

let data = {"details":{"id": 10,"name": 'John Doe',"hobbies": [{"id": 1,"name": "Football"},{"id": 2,"name": "Badminton"},{"id": 3,"name": "Running"}],"dob": '1989-12-31'}}

$('#hobbies').val(data.details.hobbies.map(o => o.name).join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="hobbies" size="25" />

Also note that your data object is missing some quotes around the name and dob properties, but I assume that was just a typo in the question otherwise you'd get no output at all.

The best solution is :

$.ajax({
  type: 'POST',
  url: "{{ route('askdata') }}",
  dataType: 'json',
  data: { 'id': $('#member_id').val(), },
  success: function(data) {
    const { details: {id, name, dob, hobbies} } = data
    $('#id').val(id);
    $('#name').val(name);
    $('#dob').val(dob);
    $('#hobbies').val(JSON.stringify(hobbies.map(hobby => {
      return {name: hobby.name}
    })));
  }
});
Related