[英]What is the fastest way to convert fields of a json into arrays in javascript?
I have a JSON file whose content is as follows, I want to replace the content of each field with arrays.我有一个内容如下的 JSON 文件,我想用数组替换每个字段的内容。
{
"ID": "GO:0051345",
"Description": "positive regulation of hydrolase activity",
"GeneRatio": "3/5",
"BgRatio": "464/15405",
"pvalue": 0.000259498331261799,
"p_adjust": 0.0446337129770295,
"qvalue": 0.0169356805665595,
"geneID": "Ptpa/Wdr35/Dnajb11",
"Count": 3
}
I have achieved desired result using the following code:我使用以下代码达到了预期的结果:
GO_data = fs.readFileSync('my_data.json');
GO_data = JSON.parse(GO_data);
var data_header = Object.keys(GO_data);
// enumerate its property names
for (var prop in GO_data) {
var arr = [];
arr.push(GO_data[prop]);
GO_data[prop] = arr;
}
//write the converted json
fs.writeFileSync('my_data_arr.json', JSON.stringify(GO_data), 'utf8');
content of 'my_data_arr.json' looks like below (as desired), 'my_data_arr.json' 的内容如下所示(根据需要),
{
"ID": [
"GO:0051345"
],
"Description": [
"positive regulation of hydrolase activity"
],
"GeneRatio": [
"3/5"
],
"BgRatio": [
"464/15405"
],
"pvalue": [
0.000259498331261799
],
"p_adjust": [
0.0446337129770295
],
"qvalue": [
0.0169356805665595
],
"geneID": [
"Ptpa/Wdr35/Dnajb11"
],
"Count": [
3
]
}
I would like to learn a better and faster way to achieve the same.我想学习一种更好更快的方法来实现相同的目标。 Any suggestions?有什么建议?
You don't need to create the array and push into it separately.您不需要创建数组并单独推入它。 Just use an array literal with the value in it:只需使用带有其中值的数组文字:
for (var prop in GO_data) {
GO_data[prop] = [GO_data[prop]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.