Ad
Convert AJAX Response Of Objects Array To A JSON Object
I have a sample endpoint here which has a JSON data, but for any reason I do not understand why it does return [object Object]
.
I have a previous code which was a bit confusing, but luckily I saw another answer that was clearer.
function generateTable(data, selId){
var cnt = "<table border=1>";
cnt += "<tr>";
$.each(JSON.parse(data), function(key,value){
cnt += "<td><strong>" + key + "</strong></td>";
});
cnt += "<tr>";
/* cnt += "<tr>";
$.each(obj, function(key,value){
cnt += "<td>" + value + "</td>";
});
cnt += "<tr>"; */ This part was commented because the conversion above does not work.
cnt += "</table>";
$(selId).html(cnt);
}
function createTableData(APIurl, selId){
$.getJSON("http://jsonplaceholder.typicode.com/posts", function(data){
generateTable(data, selId);
});
}
When I try to alert the data returned, it return [object Object], [object Object], ...
and so on. How do I convert the JSON data from the API to an array where I can access inside my generateTable
function? Thanks for the help.
Ad
Answer
You need to iterate over the array
var cnt = "<table border=1>";
for (var i=0, len=data.length; i<len; i++){
var row = data[i];
cnt += "<tr>";
$.each(row, function(key,value){
cnt += "<td><strong>" + key + "</strong></td>";
});
cnt += "</tr>";
}
cnt += "</table>";
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad