How to format the JSON object key/value pair

后端 未结 1 1906
野趣味
野趣味 2021-01-15 03:38

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



        
相关标签:
1条回答
  • 2021-01-15 04:16

    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);
    

    Output is:

    [ 
      { 
        headers: [ 'id', 'actionname', 'actionid' ],
        values: [ '793', 'test_bsc_interface', '100' ] 
      } 
    ]
    

    To get the result you want, just do result[0]

    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.

    Revised answer according to your comment (1 header line and all value lines in an array):

    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);
    

    and the output is:

    { 
      headers: [ 'id', 'actionname', 'actionid' ],
      values: [ 
        [ '714', 'test_bsc_interface', '100' ],
        [ '715', 'list_all_available_interfaces', '103' ],
        [ '716', 'check_tt', '101' ] 
      ] 
    }
    
    0 讨论(0)
提交回复
热议问题