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 usemap()
to build an array of the hobby names which you can thenjoin()
together to form a single string:Also note that your
data
object is missing some quotes around thename
anddob
properties, but I assume that was just a typo in the question otherwise you’d get no output at all.The best solution is :