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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yes, this one with the wrapper was integrated and proven to work well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.