从键,值对构造多列表

时间:2018-08-17 01:26:45

标签: javascript json d3.js

我有以下来自数据库表的JSON

[{"name":"field1","value":Jim,"tieRef":1},{"name":"field2","value":120.11,"tieRef":1}, 
{"name":"field3","value":AAA,"tieRef":1},{"name":"field1","value":Stacy,"tieRef":2},
{"name":"field2","value":34.10,"tieRef":2},{"name":"field3","value":BBB,"tieRef":2}]

我需要构造一个如下所示的HTML表。与同一行相关的值应由tieRef属性标识。

field1 | field2 | field3
-------------------------
JIm    | 120.11 |  AAA
-------------------------
Stacy  | 34.10  |  BBB

列名称应从“名称”属性中提取。为了提取和汇总单个列下的值,我使用了下面列出的d3.js

var transformed = d3.nest()
 .key(function(d) { return d.name; })
 .object(data);

通过此操作,我能够将原始JSON转换为以下内容

{"field1":[
    {"name":"field1","value":"Jim","tieRef":1}, 
    {"name":"field1","value":"Stacy","tieRef":2}],
"field2":[
    {"name":"field2","value":120.11,"tieRef":1}, 
    {"name":"field2","value":34.1,"tieRef":2}],
"field3":[
    {"name":"field3","value":"AAA","tieRef":1},
    {"name":"field3","value":"BBB","tieRef":2}]}

但是我不确定这是否需要正确的转换才能使构造HTML表更加容易。请建议对JSON进行更好的转换,以便我可以遍历并构造表

有人知道如何以优雅的方式实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

tieRef上输入键,然后在name上输入键,可以很好地转换JSON。首先使用d3做以下操作

var data = [{"name":"field1","value":"Jim","tieRef":1},
{"name":"field2","value":120.11,"tieRef":1},
{"name":"field3","value":"AAA","tieRef":1},
{"name":"field1","value":"Stacy","tieRef":2},
{"name":"field2","value":34.10,"tieRef":2},
{"name":"field3","value":"BBB","tieRef":2}];

var transform = d3.nest()
 .key(function(d) { return d.tieRef; })
 .key(function(d) { return d.name; })
.object(data);

这会将JSON转换为以下内容。

{"1":
  {"field1":
            [{"name":"field1","value":"Jim","tieRef":1}],
   "field2": 
            [{"name":"field2","value":120.11,"tieRef":1}],
   "field3": 
            [{"name":"field3","value":"AAA","tieRef":1}]
  },
 "2":
   {"field1": 
            [{"name":"field1","value":"Stacy","tieRef":2}],
    "field2": 
            [{"name":"field2","value":34.1,"tieRef":2}],
    "field3": 
            [{"name":"field3","value":"BBB","tieRef":2}]
    }
   }

然后通过行号1,2,..进行迭代,并构造表或进一步转换JSON