N.Malloul N.Malloul - 2 months ago 15
Javascript Question

Create an array of objects Jquery

I have a table field which I populate dynamically.

<table id="list" class="table table-striped ui-widget ui-widget-content">
<thead>

<tr class="ui-widget-header">
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Expression</th>
<th>Variable</th>
<th>Default</th>
<th>Date pattern</th>
<th>Readable</th>
<th>Writable</th>
<th>Required</th>
</tr>
</thead>
<tbody>

</tbody>




I populate it with data I get from a dialog modal.
This is a function I use to populate the table

$("#list tbody").append("<tr>"+
"<td>" + id.val() + "</td>" +
"<td>" + name_re.val() + "</td>" +
"<td>" + type.val() + "</td>" +
"<td>" + expression.val() + "</td>" +
"<td>" + variable.val() + "</td>" +
"<td>" + defaut.val() + "</td>" +
"<td>" + pattern.val() + "</td>" +
"<td>" + readable + "</td>" +
"<td>" + writable + "</td>" +
"<td>" + required + "</td>" +
"<td>" +"<button type='button' class='removebutton' title='Remove this propertie'>"+"</button>" +
"<button type='button' class='editbutton' title='Edit this propertie'>"+"</button>" +
"<button type='button' class='savebutton' title='save propertie changes'>"+"</button>" +"</td>"+
"</tr>"
);


Now I created a function to get the data from the table and push them into an array of objects, as each object represent the data of a single row from the table.
This is the function I use to get the data

function getPropertiesListData(){
var propertiesList=[];
var id,
type,
expression,
variable,
defaut,
pattern,
readable,
writable,
required,
name;

$("#list").find('tr').each(function(){
var $tds=$(this).find('td');
propertiesList.push({
id:$tds.eq(0).text();
name:$tds.eq(1).text();
type:$tds.eq(2).text();
expression:$tds.eq(3).text();
variable:$tds.eq(4).text();
defaut:$tds.eq(5).text();
pattern:$tds.eq(6).text();
readable:$tds.eq(7).text();
writable:$tds.eq(8).text();
required:$tds.eq(9).text();

});
});
return propertiesList;}


But when I run, I have this error in the output of the navigator console

Uncaught SyntaxError: Unexpected token ;


this error is about the line:

id:$tds.eq(0).text();


Can you help me to resolve this, or tell me where I'm wrong, or tell me a way to get the data from the table and store them into an array.

Answer Source

Change your code like this:

propertiesList.push({
            id:$tds.eq(0).text(),
            name:$tds.eq(1).text(),
            type:$tds.eq(2).text(),
            expression:$tds.eq(3).text(),
            variable:$tds.eq(4).text(),
            defaut:$tds.eq(5).text(),
            pattern:$tds.eq(6).text(),
            readable:$tds.eq(7).text(),
            writable:$tds.eq(8).text(),
            required:$tds.eq(9).text(),

    });