Home > database >  I want to make HTML table from array
I want to make HTML table from array

Time:10-30

The task is to fill the table with data from arrays id, name and price. What am I doing wrong?

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table ><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data, function(index, value){ 

                table  = ('<tr>');
                table  = ('<td>'   value.id   '</td>');
                table  = ('<td><img src="'   value.name   '"></td>');
                table  = ('<td>'   value.price   '</td>');
                table  = ('</tr>');
            });

            table  = '</table>'; 
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

It doesn't work, because your input data is not organised as an array of objects, but as an object of arrays (which is less OOP).

As I prefer the array of objects as data structure, I would suggest to (temporarily) convert to that structure, and then your loop will work as expected:

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
var table = '<table ><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(array, function(index, value){ 

                table  = ('<tr>');
                table  = ('<td>'   value.id   '</td>');
                table  = ('<td><img src="'   value.name   '"></td>');
                table  = ('<td>'   value.price   '</td>');
                table  = ('</tr>');
            });

            table  = '</table>'; 
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

As an unrelated remark, I would suggest using jQuery more in the process of building the table. This will also avoid problems you might get when your data has < or & characters in it immediately followed by letters, as that would be interpreted as HTML:

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;

$('#tableContainer').empty().append($("<table>").addClass("mainTable").append(
    $("<tr>").append(
        $("<th>").text("id"),
        $("<th>").text("name"),
        $("<th>").text("price")
    ),
    ...array.map(value =>
        $("<tr>").append(
            $("<td>").text(value.id),
            $("<td>").append($("<img>", { src: value.name })),
            $("<td>").text(value.price)
        )
    )
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your data structure is not iterable. So you need to either change your data structure to be a list [{id: '1111', name: 'name1', price: 1111}], or you need to assume that all lists (id, name, price) are the same length, and use that length for the iteration.

As other answers detail how to use an iterable data structure, I'll handle the other method, where your data is already in this format, and won't change.

For this method, find the length of one property (id, name or price), and iterate through all of them using the index. Here is an example.

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table ><tr><th>id</th><th>name</th><th>price</th></tr>';
data.id.forEach((value, index) => {
    table  = ('<tr>');
    table  = ('<td>'   data.id[index]   '</td>');
    table  = ('<td><img src="'   data.name[index]   '"></td>');
    table  = ('<td>'   data.price[index]   '</td>');
    table  = ('</tr>');
});
table  = '</table>'; 
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You're processing the data as if it were structured as a single array, like this:

data = [
  {
    id: 1986,
    name: "name1",
    price: 1148
  }
]

However, your data contains three arrays, not one:

data = {
  id: [...],
  name: [...],
  price: [...],
}

If the data was structured like the first example, then value would contain an object for each array element, with the properties id, name and price available.

An option is to convert the first data structure to the second:

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
    id: id,
  name: data.name[index],
  price: data.price[index]
}))

Then, use the mappedData and access the properties as you're already doing, as follows:

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
    id: id,
  name: data.name[index],
  price: data.price[index]
}))
var i = 0;
var table = '<table ><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(dataMapped, function(index, value){ 

                table  = ('<tr>');
                table  = ('<td>'   value.id   '</td>');
                table  = ('<td><img src="'   value.name   '"></td>');
                table  = ('<td>'   value.price   '</td>');
                table  = ('</tr>');
            });

            table  = '</table>'; 
$('#tableContainer').html(table);

CodePudding user response:

var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table ><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data["id"], function(index, value){ 

                table  = ('<tr>');
                table  = ('<td>'   value   '</td>');
                table  = ('<td><img src="'   data["name"][index]   '"></td>');
                table  = ('<td>'   data["price"][index]   '</td>');
                table  = ('</tr>');
            });

            table  = '</table>'; 
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There ways to iterate the data as you defined it but I think it's better to define it in a proper way, as an array of entities ($.each is to iterate through an array):

[
 {
   "id": "1986",
   "name": "name1",
   "price": 1148
 },
 {
   "id": "1990",
   "name": "name2",
   "price": 1396
 },
];

CodePudding user response:

Without changing the input you can do this.

var data = {
  "id": ["1986", "1990", "1989", "1985", "1988", "1987"],
  "name": ["name1", "name2 ", "name3 ", "name4", "латунь матовая ", "name5"],
  "price": [1148, 1396, 2775, 1270, 1396, 1270]
};


document.getElementById("tableContainer").innerHTML = data.id
  .map((id,i) => `<tr><td>${id}</td>
    <td><img src="${data.name[i]}"></td>
    <td>${data.price[i]}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <table class="mainTable">
    <thead>
      <tr>
        <th>id</th>
        <th>name</th>
        <th>price</th>
      </tr>
    </thead>
    <tbody id="tableContainer"></tbody>
  </table>
</div>
<iframe name="sif6" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I also recommmend you change the input to an array of objects. It makes the parsing simpler

var data = [
  { "id": "1986", "name": "name1", "price": 1148},
  { "id":"1990",  "name": "name2", "price": 1396},
  { "id":"1989",  "name": "name3", "price": 2775},
  { "id":"1985",  "name": "name4", "price": 1270},
  { "id":"1988",  "name": "латунь матовая ", "price": 1396},
  { "id":"1987",  "name": "name5", "price": 1270}
];


document.getElementById("tableContainer").innerHTML = data
  .map(({id,name,price}) => `<tr><td>${id}</td>
    <td><img src="${name}"></td>
    <td>${price}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <table class="mainTable">
    <thead>
      <tr>
        <th>id</th>
        <th>name</th>
        <th>price</th>
      </tr>
    </thead>
    <tbody id="tableContainer"></tbody>
  </table>
</div>
<iframe name="sif7" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related