简体   繁体   English

使用JavaScript从JSON值加载HTML表

[英]Loading a HTML table from JSON values with JavaScript

I have a JSON file that looks like this https://pastebin.com/ushcMpwY , and I would like to load it into a HTML table that has 6 columns (group, name, registration 1, registration 2, week, half term). 我有一个类似于https://pastebin.com/ushcMpwY的JSON文件,我想将其加载到具有6列(组,名称,注册1,注册2,星期,半年)的HTML表中。 Here is an example of what I would like it to produce: 这是我想要产生的示例:

<table id="people">
    <tr>
        <th>Group name</th>
        <th>Name</th>
        <th>Registration 1</th>
        <th>Registration 2</th>
        <th>Week</th>
        <th>Half term</th>
    </tr>

    <!-- Where JS inserted HTML begins -->
    <tr class="9" id="HA09_000">
        <td>9</td>
        <td>Wyatt Fedlt</td>
        <td>R</td>
        <td>R</td>
        <td>0</td>
        <td>1</td>
    </tr>

    ...

    <!-- Where JS inserted HTML ends -->

</table>

It was suggested to me that I should use an OOP approach such as this one https://pastebin.com/0TRrLT6n , and while I was able to get that to work with regards to printing out the data, it didn't seem like an approach that would be very useful for making the actual table. 有人建议我应该使用一种OOP方法,例如https://pastebin.com/0TRrLT6n ,虽然我能够使它在打印数据方面起作用,但似乎并没有这对于制作实际表格非常有用。 At the moment it is very buggy. 目前,这是非常容易的错误。 It produces a table that looks like this: http://prntscr.com/m9eh44 and I just don't know how to get it to make one like I've described above, and so I'd rather go back to a procedural approach that I understand like the one I have referenced in the Pseudo Code below. 它产生一个看起来像这样的表: http : //prntscr.com/m9eh44而且我只是不知道如何使它成为像我上面描述的那样,所以我宁愿回到一个过程我理解的方法就像我在下面的伪代码中引用的方法。

Initially, I tried to write some code what would work like this Pseudo Code: 最初,我尝试编写一些类似于此伪代码的代码:

TABLE = GET_TABLE_BY_ID('people')
PERSON_COUNT = 0
FOR GROUP IN DATA:
    FOR PERSON IN GROUP:
        ROW = TABLE.INSERTROW(PERSON_COUNT)
        ROW.CLASSLIST.ADD(GROUP.NAME)
        ROW.ID.ADD(PERSON.ID)
        CELL = ROW.INSERTCELL(0)
        CELL.INNERHTML = GROUP.NAME
        INFO_COUNT = 0
        FOR INFO IN PERSON:
            CELL = ROW.INSERTCELL(INFO_COUNT)
            CELL.INNERHTML = INFO
            INFO_COUNT++
        PERSON_COUNT++

That resulted in some actual code like this (at that point I was just trying to print out the values since it would then be simple enough to convert it into code to generate the table). 这就产生了这样的实际代码(当时,我只是试图打印出这些值,因为这样就足够简单,可以将其转换为代码以生成表)。

$.getJSON("http://localhost:8000/data.json", function(data) {
    output_json(data);
});

function output_json(data) {
    var i, j, k;
    for (i = 0; i < Object.keys(data).length; i++) {
        group_ = Object.values(data)[i];
        for (j = 0; j < Object.keys(group_).length; j++) {
            person = Object.values(group_)[j];
            person_id = Object.keys(person)[0];
            console.log(Object.keys(data)[i]); // Group
            console.log(person_id); // ID
            for (k = 0; k < Object.keys(person).length; k++) {
                person_info = Object.values(person)[k][0];
                console.log(person_info); // Information
            }
        }
    }
}

I was hoping for this code to print out the data that I would like to input into the table for each person, ie their group, their name, etc. I wanted it to do this: 我希望这段代码为每个人打印出我想输入到表中的数据,即他们的小组,他们的姓名等。我希望这样做:

9 9

HA09_000 HA09_000

Wyatt Feldt 怀亚特·费尔德

R [R

R [R

0 0

1 1

However, my code currently produces this: 但是,我的代码当前产生此结果:

9 9

HA09_000 HA09_000

{name: "Wyatt Feldt", registration_1: "R", registration_2: "R", week: 0, half_term: 1} {名称:“怀亚特·费尔德”,注册_1:“ R”,注册_2:“ R”,星期:0,半年:1}

If someone could show me how to at least print the values then (as long as it is procedural), I'm confident I can add the table part in myself. 如果有人可以告诉我至少如何打印这些值(只要它是过程性的),我相信我可以在自己中添加表格部分。 However, if you think this really should be OOP then I would hugely appreciate it if you could explain to me how I could implement the table part as well. 但是,如果您认为这确实应该是OOP,那么如果您能向我解释我也可以如何实现表部分,我将不胜感激。 I know I can make this work with 4 for loops, but that's very inefficient and I'm confident it can be done in 3 much clearer loops like I've laid out in my Pseudo Code. 我知道我可以使用4个for循环来完成这项工作,但这效率很低,我相信可以像我在伪代码中所列出的那样在3个更清晰的循环中完成此工作。

Thanks. 谢谢。

IMO a more readable/elegant solution is to separate concerns a little and use pure functions... IMO更具可读性/优雅的解决方案是将关注点稍微分开,并使用纯函数...

  1. Flatten all your data 整理所有数据
  2. Build HTML table rows 建立HTML表格行
  3. Add to table 添加到表格
    let rowKeys = Object.keys(data);

    // iterate over the 'first level' keys with the goal of extracting the values needed in the final objects (elemClass), while then extracting the 'second level' object (group) so that you can access its data.
    let rowsFlattened = rowKeys.reduce((acc,key) => {
            let elemClass = key,
                group = data[key];

             let people = group.reduce((acc2,groupObj)=> {
                    let elemId = Object.keys(groupObj)[0],
                        person = groupObj[elemId][0];

                        return [
                            ...acc2,
                            {
                                ...person,
                                className: elemClass,
                                id: elemId
                            }
                        ]
                },[])

                // these 'spread operators' merge either objects or arrays, in this case an array.
                return [
                    ...acc,
                    ...people
                ]

        // this '[]' is the starting accumulator, which you have access to in the 'acc' parameter above. After each iteration this 'acc' value is replaced by whatever value is returned in the previous iteration. 
        },[]);

    // 
    let rowsHTML = rowsFlattened.map(obj => {
            let { className, id, name, registration_1, registration_2, week, half_term} = obj;
            return `
                <tr class="${className}" id="${id}">
                    <td>${className}</td>
                    <td>${name}</td>
                    <td>${registration_1}</td>
                    <td>${registration_2}</td>
                    <td>${week}</td>
                    <td>${half_term}</td>
                </tr>
            `
        })  

        $('#people').html(rowsHTML);

My solution is a little long so please see the below jsFiddle... 我的解决方案有点长,所以请参阅下面的jsFiddle ...

https://jsfiddle.net/u1ekga7y/ https://jsfiddle.net/u1ekga7y/

I'm guessing you want the person info to be in an array? 我猜您想将个人信息放入数组中? Add another loop to go through the person_info object keys and values.. 添加另一个循环以遍历person_info对象的键和值。

        for (k = 0; k < Object.keys(person).length; k++) {
            person_info = Object.values(person)[k][0];
            console.log(person_info); // Information
        }

To

        var person_info_data = [];
        for (k = 0; k < Object.keys(person).length; k++) {
            person_info = Object.values(person)[k][0];
            for (l = 0; l < Object.keys(person_info).length; l++) {
                person_info_data.push(Object.values(person_info)[l])
            }
            console.log(person_info_data); // Information
        }

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

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