Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Last active July 17, 2019 10:47
Show Gist options
  • Save JeffreyZhao/d131293c3f7db2e552c6 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/d131293c3f7db2e552c6 to your computer and use it in GitHub Desktop.

打印表头

小明正在用JavaScript写一个日志分析程序。该程序会将日志转化为CSV文件,以便在Excel等应用中加载为一个表格。现在他在生成表头上遇到了困难。

他需要实现如下一个方法:

function printLine(array) {
    console.log(array.join(","));
}

function printHeader(obj) {
	/* 使用 printLine 输出内容*/
}

输入

小明获取一个对象,需要根据这个对象的结构生成表头。例如:

{
	Process: {
		CpuUsage: 0
		VirtualMemory: 0,
		PrivateMemory: 0
	},
	Subscriptions: {
		Order: {
			TotalCount: 0,
			LastMinute: 0,
			Failed: 0
		},
		User: {
			TotalCount: 0
			LastMinute: 0
		}
	}
}

由于表头仅和对象结构相关,因此无需关注字段的值。

输出

输出为一行至多行文本,为CSV格式,字段之间以逗号隔开(简化问题起见,字段本身不包含逗号)。

如上输入,则需要得到以下输出:

Process,,,Subscriptions
CpuUsage,VirtualMemory,PrivateMemory,Order,,,User
,,,TotalCount,LastMinute,Failed,TotalCount,LastMinute

该CSV文件内容使用Excel打开便会得到以下表格(请忽略格式):

ProcessSubscriptions
CpuUsageVirtualMemoryPrivateMemoryOrderUser
TotalCountLastMinuteFailedTotalCount LastMinute

总而言之,是将对象结构转化为如上表头。

@bao-qian
Copy link

js 版本,基本跟上面的 python 版本一样。

function printLine(array) {
    console.log(array.join(","));
}

function printHeader(obj) {
    var table = [];
    var width = 0;

    function create_table(header, height) {
        for (var key in header) {
            var line = table[height] || [];
            var n = width - line.length;
            line.push.apply(line, new Array(n).fill(''));
            line.push(key);

            if (typeof header[key] == "object") {
                create_table(header[key], height + 1)
            }
            width = Math.max(line.length, width);
            table[height] = line
        }
    }

    create_table(obj, 0);
    table.forEach(printLine);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment