2

I have a Node.js API that returns JSON formatted like this:

[
    {
        "id" : "1",
        "tstamp": "2017-06-01T00:00:00.000Z",
        "dmemberprofiles","48400"
        "dgroupprofiles","4800"
        "msclprofiles","400"
    },
    {
        "id" : "2",
        "tstamp" : "2017-06-02T00:00:00.000Z",
        "dmemberprofiles","48700"
        "dgroupprofiles","4900"
        "msclprofiles","410
    }
]

How do I make Node.js return the JSON, looking like this:

{
    "header": [
        "id",
        "tstamp",
        "dmemberprofiles",
        "dgroupprofiles",
        "msclprofiles"
    ],
    "data": [
        {
            "id" : "1",
            "tstamp" : "2017-06-01T00:00:00.000Z",
            "dmemberprofiles","48400"
            "dgroupprofiles","4800"
            "msclprofiles","400"
        },
        {
            "id" : "2",
            "tstamp" : "2017-06-02T00:00:00.000Z",
            "dmemberprofiles","48700"
            "dgroupprofiles","4900"
            "msclprofiles","410
        }           
    ]
}

I've looked around for other examples but haven't found a Node.js-specific solution.

MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
  • Possible duplicate of [Get array of object's keys](https://stackoverflow.com/questions/8763125/get-array-of-objects-keys) – str Jun 10 '17 at 15:39

2 Answers2

1

You could take the keys from the first object of the array with Object.keys.

var array = [{ id: "1", tstamp: "2017-06-01T00:00:00.000Z", dmemberprofiles: 48400, dgroupprofiles: 4800, msclprofiles: 400 }, { id: "2", tstamp: "2017-06-02T00:00:00.000Z", dmemberprofiles: 48700, dgroupprofiles: 4900, msclprofiles: 410 }],
    object = { header: Object.keys(array[0]), data: array };

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Assuming

var data = [
    {
        "id" : "1",
        "tstamp": "2017-06-01T00:00:00.000Z",
        "dmemberprofiles","48400"
        "dgroupprofiles","4800"
        "msclprofiles","400"
    },
    {
        "id" : "2",
        "tstamp" : "2017-06-02T00:00:00.000Z",
        "dmemberprofiles","48700"
        "dgroupprofiles","4900"
        "msclprofiles","410
    }
]

then just do:

// Add data to wrapper
var wrapper = {
    "header": [
        "id",
        "tstamp",
        "dmemberprofiles",
        "dgroupprofiles",
        "msclprofiles"
    ],
    "data": data
}

// Convert to JSON
var json = JSON.stringify( wrapper );
Julian Goacher
  • 567
  • 2
  • 6