javascriptarraysjsonrhinostringify

JSON.stringify on Arrays adding numeric keys for each array value


I am trying to convert an array to object .

Below is the array value which I am trying to transform into an object.

kbInfo : [{ "questionId": "1", "customQuestion": "What is your first car make and model", "answer": "Ford Pinto" },{ "questionId": "14", "customQuestion": "Your favorite sports", "answer": "Sleeping" } ]

This gives a result like below after doing a JSON.stringify(kbaInfo)

{"0":{ "questionId": "1", "customQuestion": "What is your first car make and model", "answer": "Ford Pinto" },"1":{ "questionId": "14", "customQuestion": "Your favorite sports", "answer": "Sleeping" }}

I want to create the result in this form.

{ "SQA": [{ "questionId": "1", "customQuestion": "What is your first car make and model", "answer": "Ford Pinto" }, { "questionId": "14", "customQuestion": "Your favorite sports", "answer": "Sleeping" } ]}

I am not able to figure out how I can create on object result like above. I am using a Rhino 1.7 engine. Is there a way I can achieve this form?


Solution

  • I suppose that you mean that kbInfo and kbaInfo are the same variable. To get that "SQA" property in your output object, you'll need to create it...

    For example:

    var kbInfo = [{ "questionId": "1", "customQuestion": "What is your first car make and model", "answer": "Ford Pinto" },{ "questionId": "14", "customQuestion": "Your favorite sports", "answer": "Sleeping" } ];
    
    var wrapped = { SQA: kbInfo };
    
    console.log(JSON.stringify(wrapped));

    From comments it seems that your input data might not be an array, but just an "array-like" object. In that case, create an array from it. This solution assumes that the input object has a length property:

    var kbInfo = { 0: { "questionId": "1", "customQuestion": "What is your first car make and model", "answer": "Ford Pinto" }, 1: { "questionId": "14", "customQuestion": "Your favorite sports", "answer": "Sleeping" }, length: 2 };
    
    var wrapped = { SQA: Array.from(kbInfo) };
    
    console.log(JSON.stringify(wrapped));