简体   繁体   English

如何从javascript中的对象数组添加表格行?

[英]How to add table row from array of objects in javascript?

How can we create table row using JavaScript我们如何使用 JavaScript 创建表格行

I was trying to create table row from array of objects in javascript using map function but somehow its throwing error我试图使用 map 函数从 javascript 中的对象数组创建表行,但不知何故其抛出错误

    const renderTableData = (result) => {
            return result.map((item, index) => {
                return (
                    <tr>
                        <td >item.Name</td>
                        <td >item.Date</td>
                        <td >item.state</td>
                    </tr>
                )
            })
        }


    const dataBinding = (result) => {
        let x = document.getElementById("tableSection");
        x.innerHTML = renderTableData(result);
    }

my html <table> <tbody id = "tableSection"> </tbody></table>我的 html <table> <tbody id = "tableSection"> </tbody></table>

You should use a template string您应该使用模板字符串

 const renderTableData = (result) => { return result.map((item, index) => { return `<tr> <td >${item.Name}</td> <td >${item.Date}</td> <td >${item.state}</td> </tr>`; }).join(''); }; const dataBinding = (result) => { let x = document.getElementById("tableSection"); x.innerHTML = renderTableData(result); }; dataBinding([ { Name: "first", Date: "2020-09-21", state: "USA" }, { Name: "first", Date: "2020-09-21", state: "USA" }, { Name: "first", Date: "2020-09-21", state: "USA" }, ]);
 <table> <tr> <th>Name</th> <th>Date</th> <th>state</th> </tr> <tbody id="tableSection"></tbody> </table>

I used template string as we need to create for each item a multiline string.我使用模板字符串,因为我们需要为每个项目创建一个多行字符串。 We could have achieved the same result with normal string but would have been much less readable.我们可以用普通字符串获得相同的结果,但可读性会差很多。


             "<tr>\
                  <td >"+item.Name+"</td>\
                  <td >"+item.Date+"</td>\
                  <td >"+item.state+"</td>\
              </tr>"

After we map over the array of objects we end up with an array of strings.在我们映射对象数组之后,我们最终得到一个字符串数组。 .join('') creates a single string out of that array and removes also the commas(if you set the innerHTML to an array, the commas between the elements will be considered as text to parse). .join('')从该数组中创建一个字符串并删除逗号(如果您将 innerHTML 设置为数组,则元素之间的逗号将被视为要解析的文本)。

When you set the innerHTML of an element, the provided string is parsed as HTML.当您设置元素的innerHTML 时,提供的字符串将被解析为HTML。 You can read more about it here你可以在这里阅读更多关于它的信息

What you did on the first place was not valid javascript code, you were using a sort of JSX您首先所做的不是有效的 javascript 代码,您使用的是一种JSX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM