JSON.stringify 在数组上为每个数组值添加数字键

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

我正在尝试将数组转换为对象。

下面是我试图转换成对象的数组值。

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

在执行 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" }}

我想以这种形式创建结果。

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

我不知道如何创建像上面那样的对象结果。我正在使用 Rhino 1.7 引擎。有什么办法可以实现这种形式吗?

我想你的意思是 kbInfokbaInfo 是同一个变量。要在输出对象中获得“SQA”属性,您需要创建它...

例如:

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

从评论看来,您的输入数据可能不是数组,而只是一个“array-like”对象。在这种情况下,从中创建一个数组。此解决方案假定输入对象具有 length 属性:

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