Skip to content
Advertisement

How to make a dropdown of the data receive from ajax response as array of objects

I want to make a dropdown in my table which is populated with the dynamic data coming from ajax response and append to the table. My postman collection looks like this.

{
    "createdDate": "2022-04-06T11:42:37.360Z",
    "enabled": true,
    "_id": "62502b868daa3b1cdbdc98e8",
    "CNIC": "40740c7d9f3a11d93e76af7f2f60887a",
    "employeeID": "LE44337",
    "fName": "HUSNAIN",
    "company": "6249fdf91399dc7a14173dcd",
    "fatherName": "husnain",
    "motherName": "momutaz",
    "spouse": "no spouse",
    "children": [{
        "_id": "62502b868daa3b1cdbdc98e9",
        "name": "hunsian",
        "age": 23232
    }, {
        "_id": "62502b868daa3b1cdbdc98ea",
        "name": "hunsian",
        "age": 12121
    }, {
        "_id": "62502b868daa3b1cdbdc98eb",
        "name": "momin",
        "age": 2323
    }
}

And below is my ajax response code in which I am appending the data into table.

success : function(response){
                        
    var trHTML = '';
    $.each(response.doc, function (i, item) {
                        
        trHTML += '<tr><td>' + item.fName + '</td><td>' + item.CNIC + '</td><td>' + item.spouse + '</td><td>'+ item.fatherName + '</td><td>' + item.motherName +'</td><td>'+ item.employeeID +'</td><td>' + item.children.map(({name, age}) => `Name: ${name} Age: ${age}`).join('  ||  ') +'</td></tr>';
    });
    $('#records_table').append(trHTML);
}

The itme.children name , age I want to make a dropdown of it into table so it looks good.

Advertisement

Answer

If you mean a dropdown like a select menĂº, this should do the job

trHTML += `... <td>
    <select>
        <option selected disabled>Click me</option>` + 
        item.children.map(({name + age}) => `<option>Name: ${name}, Age: ${age}</option>`).join('') +
    `</select></td>`;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement