问题描述
我是nodejs的新手,现在我能够从数据库中获取数据并显示为键/值对的REST API.我的输出如下图所示
I am new to nodejs, right now I am able to fetch the data from the database and display as REST API which is of key/value pair. My output looks like as shown below
[{"id":"793","actionname":"test_bsc_interface","actionid":"100"}].
但是我需要格式化为
{ "header" : [id,actionname,actionid],
"values" : [793 ,test_bsc_interface,100] ],}.
我尝试了JSON.stringfy
,并检查了几个网站,但无法正常工作.
I tried with JSON.stringfy
and checked few website but it's not working.
任何人都可以帮助我通过哪个链接或方法来帮助我.
Could any one please help me through which link I should go through or approach.
推荐答案
简单的方法是使用下划线或 lodash 模块对其进行格式化:
The easy way to do it is to use underscore or lodash module to format it:
var _ = require('lodash');
var data = [{"id":"793","actionname":"test_bsc_interface","actionid":"100"}];
var result = _.map(data, function(o) {
return {headers: _.keys(o), values : _.values(o)}
});
console.dir(result);
输出为:
[
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [ '793', 'test_bsc_interface', '100' ]
}
]
要获得所需的结果,只需执行result [0]
To get the result you want, just do result[0]
请注意,我使用_.map()代替了data [0],因为它适用于具有1个以上项的数组(查询中的数组结果).
Note that I use _.map() instead of data[0] because this will work for the array (your array result from the query) that has more than 1 item.
var _ = require('lodash');
var data = [
{ id: '714', actionname: 'test_bsc_interface', actionid: '100' },
{ id: '715', actionname: 'list_all_available_interfaces', actionid: '103' },
{ id: '716', actionname: 'check_tt', actionid: '101' }
];
var result;
if (_.size(data) > 0) {
result = {
headers: _.keys(data[0]),
values: _.map(data, function(o) {
return _.values(o);
})
};
}
console.dir(result);
,输出为:
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [
[ '714', 'test_bsc_interface', '100' ],
[ '715', 'list_all_available_interfaces', '103' ],
[ '716', 'check_tt', '101' ]
]
}
这篇关于如何格式化JSON对象键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!